在随机位置java中写入txt文件

时间:2012-06-14 16:31:56

标签: java file-handling random-access

我正在尝试将字符串写入随机位置的txt文件,即我想编辑特定的txt文件。我不想APPEND,但我想做的就是写一些字符串,比如第3行。 我使用RandomAccessFile尝试了相同的操作,但是当我写入特定的行时,它会替换该行的数据。

e.g。 A.TXT -

1
2
3
4
5

我期望的输出..

1
2

3
4
5

我使用RandomAccessFiles取得的成就

1
2

4
5


我试图在替换之前保存第3行的内容,我使用了readLine()函数,并且它不起作用,它给出了意想不到的结果。

3 个答案:

答案 0 :(得分:3)

对于内存不太大的文件:

您可以read the file into a String然后执行以下操作:

String s = "1234567890"; //This is where you'd read the file into a String, but we'll use this for an example.
String randomString = "hi";
char[] chrArry = s.toCharArray(); //get the characters to append to the new string
Random rand = new Random();
int insertSpot = rand.nextInt(chrArry.length + 1); //Get a random spot in the string to insert the random String
//The +1 is to make it so you can append to the end of the string
StringBuilder sb = new StringBuilder();
if (insertSpot == chrArry.length) { //Check whether this should just go to the end of the string.
  sb.append(s).append(randomString);
} else {
  for (int j = 0; j < chrArry.length; j++) {
    if (j == insertSpot) {
      sb.append(randomString);
    }
    sb.append(chrArry[j]);
  }
}
System.out.println(sb.toString());//You could then output the string to the file (override it) here.

对于内存太大的文件:

你可以做一些copying the file的变体,你可以在前面识别一个随机点,然后在输出流中将其写入该块的其余部分之前。以下是一些代码:

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"));

答案 1 :(得分:1)

没有API可以做到这一点。 你能做的是:

  1. 选择随机位置
  2. 转到行尾
  3. 写'\ n +'你的文字'

答案 2 :(得分:1)

您只有两个选项,追加和重写。文件没有插入方法,因为它们不支持此操作。要插入数据,必须重新写入文件的其余部分以将其移除。