对于内存不太大的文件:
您可以将文件读入字符串,然后执行以下操作:
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"));