假设我有一个名为Sample.text的文本文件。 我需要有关如何实现这一目标的建议:
运行程序前的Sample.txt: ABCD
在运行程序时,用户将输入从中间开始添加的字符串 例如:用户输入为XXX
运行程序后的Sample.txt: ABXXXCD
答案 0 :(得分:5)
基本上你已经 来重写文件,至少从中间开始。这不是Java的问题 - 这是文件系统支持的问题。
通常,执行此操作的方法是打开输入文件和输出文件,然后:
答案 1 :(得分:1)
基本思路是将文件内容读入内存,比如在程序启动时,根据需要操作字符串,然后将整个内容写回文件。
如果您担心损坏或其他什么,可以将其保存到辅助文件,然后验证其内容,删除原始文件,并将新文件重命名为与原文相同。
答案 2 :(得分:0)
实际上我做了类似你想要的东西,在这里试试这个代码,它不是一个完整但它应该给你一个明确的想法:
public void addString(String fileContent, String insertData) throws IOException {
String firstPart = getFirstPart(fileContent);
Pattern p = Pattern.compile(firstPart);
Matcher matcher = p.matcher(fileContent);
int end = 0;
boolean matched = matcher.find();
if (matched) {
end = matcher.end();
}
if(matched) {
String secondPart = fileContent.substring(end);
StringBuilder newFileContent = new StringBuilder();
newFileContent.append(firstPart);
newFileContent.append(insertData);
newFileContent.append(secondPart);
writeNewFileContent(newFileContent.toString());
}
}
答案 3 :(得分:0)
通常会创建一个新文件,但以下内容可能就足够了(对于非千兆字节的文件)。注意显式编码UTF-8;你可以省略对操作系统的编码。
public static void insertInMidstOfFile(File file, String textToInsert)
throws IOException {
if (!file.exists()) {
throw new FileNotFoundException("File not found: " + file.getPath());
// Because file open mode "rw" would create it.
}
if (textToInsert.isEmpty()) {
return;
}
long fileLength = file.length();
long startPosition = fileLength / 2;
long remainingLength = fileLength - startPosition;
if (remainingLength > Integer.MAX_VALUE) {
throw new IllegalStateException("File too large");
}
byte[] bytesToInsert = textToInsert.getBytes(StandardCharsets.UTF_8);
try (RandomAccessFile fh = new RandomAccessFile(file, "rw")) {
fh.seek(startPosition);
byte[] remainder = new byte[(int)remainingLength];
fh.readFully(remainder);
fh.seek(startPosition);
fh.write(bytesToInsert);
fh.write(remainder);
}
}
Java 7或更高版本。