BufferedWriter只在android中编写第一个单词

时间:2013-10-10 04:51:33

标签: android file-io

我有以下代码写入文件:

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

这个词

是否有人知道如何解决此问题,以便我可以在文件中写入多行?

3 个答案:

答案 0 :(得分:0)

试试这段代码,

for(int i = 0; i < 100; i++) {
    writer.write("foorbar");
    writer.write(NEW_LINE);
}
writer.close();

答案 1 :(得分: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();
      }
   }
}

答案 2 :(得分:0)

close方法会阻塞,直到所有资源都空闲为止。文档说:

  

关闭流并释放与其关联的所有系统资源。

没有关于数据内容的保证。 我建议你在关闭流之前调用flush。