gpt4 book ai didi

Java - 用户映射部分打开错误

转载 作者:行者123 更新时间:2023-11-30 09:33:29 26 4
gpt4 key购买 nike

当我尝试写入指定的文件时,出现以下错误。我试过关闭 FileInputStream 但我仍然遇到同样的问题。

相关代码如下:

错误日志:

Error: C:\Path\Hours Log.csv (The requested operation cannot be performed on a file with a user-mapped section open)

代码:

创建日志:

private void writeLog() throws IOException{

//set up vars and write directories
File yearStatDir = new File("C:\\Path);
File yearStatPath = new File(yearStatDir + "\\" + "Hours Log.csv");
String yearStatString = yearStatPath.toString();

//read the files
String existingYearLog = readLogFile(yearStatString, yearStatPath);

//write the updated file
String hoursString = "1";
String dataYear = existingYearLog + hoursString;
String folderYear = "Satistics\\Yearly data\\" + yearString;
writeFile(dataYear, ".csv", folderYear, "Hours Log");
}

写入文件:

private void writeFile(String data, String fileType, String folder, String fileName){
try{
File fileDir = new File("C:\\Path\\" + folder);
File filePath = new File(fileDir + "\\"+ fileName + fileType);
writeDir(fileDir);
// Create file
FileWriter fstream = new FileWriter(filePath);
try (BufferedWriter out = new BufferedWriter(fstream)) {
out.write(data);
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}

读取文件:

private static String readLogFile(String path, File f) throws IOException {
if (f.exists()){
try (FileInputStream stream = new FileInputStream(new File(path))) {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
fc.close();
return Charset.defaultCharset().decode(bb).toString();

}
}
else {
return "";
}
}

最佳答案

对于遇到此问题的任何人,这是我现在使用的替代代码:

private static String readLogFile(String path) throws IOException {
File f = new File(path);
if(f.exists()) {
FileInputStream fis = new FileInputStream(f);
Integer fileLength = (int) (long) f.length();
byte[] b = new byte[fileLength];
int read = 0;
while (read < b.length) {
read += fis.read(b, read, b.length - read);
}
String text = new String(b);
return text;
} else {
String text = "";
return text;
}
}

关于Java - 用户映射部分打开错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12155218/

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