如何在java中的文本文件中插入新行

时间:2014-04-09 10:30:07

标签: file merge

我想在文本文件的某些位置插入数据而不实际覆盖现有数据

2 个答案:

答案 0 :(得分:0)

如果文本文件不是太大,那么您可以将其读入ArrayList,然后操作某些要添加/编辑内容的位置,然后使用ArrayList中的内容覆盖该文件。

将文本读入ArrayList:

Scanner scanner = new Scanner(new File("filename.txt"));
ArrayList<String> fileLines = new ArrayList<String>();
while (scanner.hasNext()){
    fileLines .add(scanner.next());
}
s.close();

答案 1 :(得分:0)

你可以做一些复制文件(https://github.com/kentcdodds/Java-Helper/blob/master/src/com/kentcdodds/javahelper/helpers/IOHelper.java#L127)的变体,你可以在那里识别一个随机点,然后在输出流中将其写入该块的其余部分之前。以下是一些代码:

public static void saveInputStream(InputStream inputStream, File outputFile) throws FileNotFoundException, IOException {
  int size = 4096;
  try (OutputStream out = new FileOutputStream(outputFile)) {
    byte[] buffer = new byte[size];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
      out.write(buffer, 0, length);
      //Have length = the length of the random string and buffer = new byte[size of string]
      //and call out.write(buffer, 0, length) here once in a random spot.
      //Don't forget to reset the buffer = new byte[size] again before the next iteration.
    }
    inputStream.close();
  }

} 像这样调用上面的代码:

InputStream inputStream = new FileInputStream(new File("Your source file.whatever"));
saveInputStream(inputStream, new File("Your output file.whatever"));