2014-10-03 71 views
0

我想写一些字符到文件。为此我写了下面的代码:如何在Java中将文字写入文件?

import java.io.*; 

public class write_char { 
    public static void main(String[] args) throws IOException{ 
     String name = "shahjahan.txt"; 

     PrintWriter outFile = new PrintWriter(new FileWriter(name)); 
     String text = " Hello, how are you?"; 

     for (int i = 0 ; i < text.length() ; i++) 
     { 
      outFile.write(text.charAt(i)); 
      outFile.write("\n"); 
      } 
    } 
} 

但是文件shahjahan.text是空的。我是java的新手。请帮帮我。

是否需要使用关闭或刷新关闭文件。在C中,我们不需要关闭它。

回答

0

在代码结束时,您需要在文件编写器上调用.flush()来完成编写。这也是一个很好的做法,呼吁.close()告诉系统你完成写入文件:

后添加这是你的for循环:

outFile.flush(); 
outfile.close(); 
0

你需要调用close()(或flush()outFile

例如:

String name = "yourText.txt"; 
PrintWriter outFile = new PrintWriter(new FileWriter(name)); 
String text = " Hello, how are you?"; 
for (int i = 0; i < text.length(); i++) { 
    outFile.write(text.charAt(i)); 
    outFile.write("\n"); 
} 
outFile.close(); // you missed this part