java - java写入随机位置的txt文件

标签 java file-handling random-access

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

例如 a.txt-

1
2
3
4
5

我期望的输出..

1
2

3
4
5

我使用 RandomAccessFiles 取得了什么

1
2

4
5


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

最佳答案

对于内存来说不太大的文件:

你可以 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 进行某种变体,预先确定一个随机点,并将其写入输出流中,然后再写入该 block 的其余部分。下面是一些代码:

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

关于java - java写入随机位置的txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11037459/

相关文章:

python - 在 python 中读取/写入文件的更好方法?

c - 程序在接受用户输入后不给出任何输出

使用 RandomAccessFile 创建文件时出现 java.io.FileNotFoundException

java - 拖动后执行意外操作

java - 尝试写入文件时发生 Android ENOENT 错误

C++ 列表随机访问

java - DeleteByName 方法不适用于 RandomAccessFile

java - 我应该在发送电子邮件时使用什么异步任务或线程

java - NetBeans-JAVA 中的空布局

java - 如何使用/导入 @EnableRedisHttpSession Spring 注释?