2

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

egatxt-

1
2
3
4
5

我期望的输出..

1
2

3
4
5

我使用 RandomAccessFiles 所取得的成就

1
2

4
5


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

4

3 回答 3

3

对于内存不太大的文件:

您可以将文件读入字符串,然后执行以下操作:

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.

对于内存太大的文件:

您可以对复制文件进行某种变体,在该文件中预先确定一个随机点,然后在该块的其余部分之前将其写入输出流中。下面是一些代码:

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"));
于 2012-06-14T16:38:51.563 回答
1

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

  1. 选择一个随机位置
  2. 走到行尾
  3. 写 '\n + '你的文字'
于 2012-06-14T16:35:35.107 回答
1

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

于 2012-06-14T16:36:54.437 回答