java java中的文件覆盖——用户映射部分打开错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12308878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
file overwrite in java -- user-mapped section open error
提问by leba-lev
The following function in a java program is written with the intent to read from a file and overwrite back to the same file after.
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();
}
}
}
The error message on trying to run the program is:
尝试运行该程序时的错误消息是:
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)
Request help in resolving the error.
请求帮助解决错误。
Code for readFile
读取文件的代码
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();
}
}
Read in another thread that this is a windows issue and so MappedByteBuffer in the readFile method was the cause of the problem. Re-wrote the readFile method as below. It works!
在另一个线程中读到这是一个 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;
}
回答by Visionary Software Solutions
You need to close your file streams after opening them, or they will still be around on your system. This can lead to corruption, and errors like this. Review the Java Learning Tutorials on File I/O. This tutorialalso shows the way.
您需要在打开文件流后关闭它们,否则它们仍会在您的系统上存在。这可能会导致损坏和类似的错误。查看有关文件 I/O的Java 学习教程。本教程也展示了方法。
import java.io.*;
public class ReadWriteTextFile {
/**
* Fetch the entire contents of a text file, and return it in a String.
* This style of implementation does not throw Exceptions to the caller.
*
* @param aFile is a file which already exists and can be read.
*/
static public String getContents(File aFile) {
//...checks on aFile are elided
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
Notice the finallyblock. This ensures that the stream gets closed whether an Exception happens or not. You should use one to close your open streams.
注意finally块。这确保无论异常发生与否,流都会关闭。您应该使用一个来关闭打开的流。
回答by user207421
Memory-mappings are not closed when the underlying file is closed. Use another technique to read the file into memory, if you must. It is generally preferable to process files a piece at a time.
当底层文件关闭时,内存映射不会关闭。如果必须,请使用另一种技术将文件读入内存。通常最好一次处理一个文件。