V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
linjian
V2EX  ›  Java

new FileOutputStream(file);文件已存的话会导致在 Tomcat 闪退,是啥原因啊?

  •  
  •   linjian · 2020-06-09 09:59:42 +08:00 · 1982 次点击
    这是一个创建于 1416 天前的主题,其中的信息可能已经有所发展或是发生改变。
    public static void bytesToFile(byte[] buffer, final String filePath) throws IOException {
            File file = new File(filePath);
                File fileParent = file.getParentFile();
                if (!fileParent.exists()) {
                    fileParent.mkdirs();
    
                OutputStream output = null;
                BufferedOutputStream bufferedOutput = null;
    
                try {
                    output = new FileOutputStream(file);
                    bufferedOutput = new BufferedOutputStream(output);
                    bufferedOutput.write(buffer);
                } finally {
                    if (null != bufferedOutput) {
                        bufferedOutput.close();
                    }
    
                    if (null != output) {
                        output.close();
                    }
    
                }
    
            }
        }
    
    5 条回复    2020-06-09 15:59:11 +08:00
    BBCCBB
        1
    BBCCBB  
       2020-06-09 11:29:26 +08:00
    catch 一下看报啥异常.

    另外你这代码可以用 try-with-resource 来简化一下. ==
    dallaslu
        2
    dallaslu  
       2020-06-09 12:13:25 +08:00
    会不会是权限问题
    linjian
        3
    linjian  
    OP
       2020-06-09 13:43:48 +08:00
    权限是有的。没有任何报错信息,各种尝试之后发现文件如果已经下载过一次,第二次下载执行到 output = new FileOutputStream(file);就闪退,BufferedOutputStream 正常写不是可以覆盖文件原来内容的吗?
    pursuer
        4
    pursuer  
       2020-06-09 15:40:51 +08:00
    @linjian 你把 try 的异常 catch 住打印出来,闪退你就用控制台运行,文件被独占模式打开就不能覆盖
    calloc
        5
    calloc  
       2020-06-09 15:59:11 +08:00 via iPhone
    代码有问题,一个文件只需要 close 一次
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4430 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 01:06 · PVG 09:06 · LAX 18:06 · JFK 21:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.