2016-07-28 30 views
0

我想用相同的嘗試資源來讀取和寫入非常大的文件。請嘗試使用資源來處理其正文中拋出的異常。使用試用資源讀取和寫入文件

try (Stream<String> stream = Files.lines(Paths.get("source.txt"), Charset.defaultCharset()); 
      BufferedWriter writer = Files.newBufferedWriter(Paths.get("dest.txt"))) { 
     stream.map(String::trim).map(String::toUpperCase).forEach(writer::write); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

回答

1

拉姆達不能與檢查的異常應對這樣(寫::寫拋出IOException異常)

不幸的是,在流利用這一點,你必須把它包在這一lambda相當醜陋:

try (
    Stream<String> stream = Files.lines(Paths.get("source.txt"), Charset.defaultCharset()); 
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("dest.txt"))) { 
    stream.map(String::trim) 
    .map(String::toUpperCase) 
    .forEach(s -> { 
     try { 
      writer.write(s); 
     } catch(IOException e) { 
      throw new RuntimeException(e); 
     } 
    }); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

感謝@mtj,它的工作原理,但對可讀性不好 – ravthiru

相關問題