2012-08-28 30 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; 
    } 
}