2012-08-28 25 views
2

当我尝试写入指定的文件时,它出现了下面的错误。我试过关闭FileInputStream,但我仍然遇到同样的问题。Java - 用户映射节打开错误

下面是相关代码:

错误日志:

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 ""; 
    } 
} 
+1

看一看http://stackoverflow.com/ question/3602783/file-access-synchronized-on-java-object – MadProgrammer

+0

干杯,真的有帮助。你推荐使用什么其他文件读取器来代替? – Nick

+1

您可以尝试使用RandomAccessFile – MadProgrammer

回答

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