[英]writing to a txt file in random location java
我正在嘗試在隨機位置將字符串寫入txt文件,即我想編輯特定的txt文件。 我不想追加,但是我要做的就是在第3行說一些字符串。我使用RandomAccessFile嘗試了相同的操作,但是當我寫到特定行時,它將替換該行的數據。
egatxt-
1
2
3
4
五
我期望的輸出。
1
2
嗨
3
4
五
我使用RandomAccessFiles實現了什么
1
2
嗨
4
五
我嘗試在替換之前保存第3行的內容,為此使用了readLine()函數,該函數不起作用,給出了意外的結果。
對於內存不足的文件:
您可以將文件讀入字符串 ,然后執行以下操作:
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"));
沒有API可以做到這一點。 您可以做的是:
您只有兩個選項,追加和覆蓋。 沒有文件的插入方法,因為它們不支持此操作。 要插入數據,必須重寫文件的其余部分以將其向下移動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.