3

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

以下是相关代码:

错误日志:

错误:C:\Path\Hours Log.csv(请求的操作无法在打开了用户映射部分的文件上执行)

代码:

创建日志:

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 "";
    }
}  
4

1 回答 1

2

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

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;
    }
}
于 2012-09-07T04:28:36.090 回答