V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
linjian
V2EX  ›  Java

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

  •  
  •   linjian · Jun 9, 2020 · 2863 views
    This topic created in 2158 days ago, the information mentioned may be changed or developed.
    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 replies    2020-06-09 15:59:11 +08:00
    BBCCBB
        1
    BBCCBB  
       Jun 9, 2020
    catch 一下看报啥异常.

    另外你这代码可以用 try-with-resource 来简化一下. ==
    dallaslu
        2
    dallaslu  
       Jun 9, 2020
    会不会是权限问题
    linjian
        3
    linjian  
    OP
       Jun 9, 2020
    权限是有的。没有任何报错信息,各种尝试之后发现文件如果已经下载过一次,第二次下载执行到 output = new FileOutputStream(file);就闪退,BufferedOutputStream 正常写不是可以覆盖文件原来内容的吗?
    pursuer
        4
    pursuer  
       Jun 9, 2020
    @linjian 你把 try 的异常 catch 住打印出来,闪退你就用控制台运行,文件被独占模式打开就不能覆盖
    calloc
        5
    calloc  
       Jun 9, 2020 via iPhone
    代码有问题,一个文件只需要 close 一次
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5665 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 07:42 · PVG 15:42 · LAX 00:42 · JFK 03:42
    ♥ Do have faith in what you're doing.