gpt4 book ai didi

java - java中的文件覆盖——用户映射部分打开错误

转载 作者:搜寻专家 更新时间:2023-11-01 00:57:40 24 4
gpt4 key购买 nike

<分区>

java 程序中的以下函数是为了从文件中读取并在之后覆盖回同一文件而编写的。

public static void readOverWrite(File dir) throws IOException {
for (File f : dir.listFiles()) {
String[] data = readFile(f).split("\n");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) {
for (int i = 0; i < data.length; i++) {
writer.write((data[i]+"\n"));
}
writer.close();
}
}
}

尝试运行程序时的错误信息是:

Exception in thread "main" java.io.FileNotFoundException: ..\..\data\AQtxt\APW19980807.0261.tml (The requested operation cannot be performed on a file with a user-mapped section open)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileWriter.<init>(Unknown Source)
at General.SplitCreationDate.splitLine(SplitCreationDate.java:37)
at General.SplitCreationDate.main(SplitCreationDate.java:53)

请求帮助解决错误。


读取文件的代码

protected static String readFile(File fullPath) throws IOException {
try(FileInputStream stream = new FileInputStream(fullPath)) {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
stream.close();
return Charset.defaultCharset().decode(bb).toString();
}
}

在另一个线程中读到这是一个 Windows 问题,因此 readFile 方法中的 MappedByteBuffer 是问题的原因。如下重写了 readFile 方法。有用!

protected static String readFile(File fullPath) throws IOException {
String string = "";
try (BufferedReader in = new BufferedReader(new FileReader(fullPath))) {
String str;
while ((str = in.readLine()) != null) {
string += str + "\n";
}
}
return string;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com