0

我有以下代码写入文件:

FileWriter out = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(out);


writer.write("Input String"); //Enter the string here
writer.newLine();
writer.write("Input String 2"); //Enter the string here

writer.close();

我希望它输出的是

Input String
Input String 2

我得到的只是这个词Input

有谁知道如何解决这个问题,以便我可以将多行写入文件?

4

3 回答 3

0

试试这个代码,

for(int i = 0; i < 100; i++) {
    writer.write("foorbar");
    writer.write(NEW_LINE);
}
writer.close();
于 2013-10-10T04:59:17.670 回答
0

或者你可以试试这个。。

 public class BufferedWriterDemo {
   public static void main(String[] args) throws IOException {

      StringWriter sw =null;
      BufferedWriter bw = null;
      String s = "Hello World!!";

      try{
         // create new string writer
         sw = new StringWriter();

         // create new buffered writer
         bw = new BufferedWriter(sw);

         // write string sequence to buffered writer
         bw.write(s, 0, 5);

         // write new line to the buffered writer
         bw.newLine();

         // write the next string sequence to buffered writer
         bw.write(s, 6, s.length()-6);

         // releases all bytes to the underlying stream
         bw.flush();

         // print
         System.out.print(sw.getBuffer());

      }catch(Exception e){

         // if any I/O error occurs
         e.printStackTrace();
      }finally{

         // releases system resources from the streams
         if(sw!=null)
            sw.close();
         if(bw!=null)
            bw.close();
      }
   }
}
于 2013-10-10T05:00:54.363 回答
0

close 方法会阻塞,直到所有资源都可用。文档说:

关闭流并释放与其关联的任何系统资源。

对数据的内容没有任何保证。我建议您在关闭流之前调用flush。

于 2013-10-10T05:04:12.893 回答