2017-08-06 154 views
0

所以我使用这种方法写入文件,它在Windows上完全正常工作,但是在Mac上运行时它会创建文件,但它们是空的。BufferedWriter在Windows上工作,但不能在Mac上工作

public static void writeLinesToTextFile(String path, String[] lines) { 
File file = new File(r + path); 
if (!file.exists()) { 
    try { 
     file.getParentFile().mkdirs(); 
     file.createNewFile(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

    BufferedWriter bw; 

    try { 

     bw = new BufferedWriter(new FileWriter(file.getPath())); 
     file.delete(); 
     file.createNewFile(); 

     for (int i = 0; i < lines.length; i++) { 
      //System.out.println(lines[i]); 
      bw.write(lines[i]); 
      bw.write(System.getProperty("line.separator")); 
     } 
     bw.flush(); 
     bw.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

我知道数据是正确的,因为它打印正确。 感谢您的帮助,这真的让我失望。

+0

而不是'bw.write(System.getProperty(“line.separator”))',你可以使用'bw.newLine()':https://docs.oracle.com/javase/8/docs/ api/java/io/BufferedWriter.html#newLine-- – Jeffrey

+0

仅供参考,我已编辑我的答案以添加此行为的解释。 –

回答

1

创建BufferedWriter后,请勿删除file。在Linux中,每个文件都有一个唯一的文件句柄,所以删除并重新创建具有相同路径的文件会创建2个不同的文件句柄。我不知道Windows做了什么,因为我不认为它是一个真正的操作系统,但从你的文章看来,它使用相同的文件句柄。

相关问题