在Java中修改特定行的文件

时间:2014-03-07 15:47:36

标签: java arraylist bufferedreader fileoutputstream

我正在编写一种方法,允许我在文件中的特定点输入一行,例如.txt或.vbs脚本。我遇到的问题是写回部分,输出文件是空白的 - 不包含我的ArrayList scriptCollection的条目。这是我的测试方法代码;

public void testMethod()throws Exception 
{

  BufferedReader br = new BufferedReader(new FileReader("C:/Users/jchild/Desktop/PrintScript.vbs"));
  int indexNo = 1; 
  int appendAt=0;  
  String line;            
  while((line = br.readLine()) != null)
  {            
      scriptCollection.add(line);
      if(line.contains("Add at this point"))
      {
          System.out.println("Successfully read and compared"); //this is just for test output
          appendAt = appendAt + indexNo;
      }
      indexNo++;
   }   
  br.close();
  scriptCollection.add(appendAt++,"Appended here"); 
  System.out.println(scriptCollection.toString()); //this is just for test output

  //here's what's causing the problem
  FileOutputStream fos = new FileOutputStream("C:/Users/jchild/Desktop/PrintScript.txt"); 
  PrintWriter is = new PrintWriter(fos);
  for(String temp : scriptCollection) 
  {
      is.println(temp);
  }                     
  scriptCollection.clear();
}

1 个答案:

答案 0 :(得分:1)

你必须关闭溪流。