Java学习笔记 (二十七) 使用NIO写文件
生活随笔
收集整理的這篇文章主要介紹了
Java学习笔记 (二十七) 使用NIO写文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用Channel 寫數據
代碼如下:
public static void main(String []args){try(FileOutputStream fos=new FileOutputStream("fos.txt")){//獲取文件通道FileChannel fc=fos.getChannel();//創建 字節緩沖區ByteBuffer byteBuffer=ByteBuffer.allocate(1024);byteBuffer.put("I LOVE YOU".getBytes());//翻轉byteBuffer.flip();//寫出緩沖區的數據fc.write(byteBuffer);}catch (Exception e){e.printStackTrace();}}創建NIO Path 對象
Path對象是對 文件 或者目錄的路徑的引用. Path 類似于 FIle ,可以引用文件系統的絕對路徑或者相對路徑。
Path 創建對象可以使用 工廠類 java.nio.files.Paths ,它有一個靜態的get()方法。
如下:
使用java.nio.file.Files中的 write() 方法來寫入文件
代碼如下:
public static void main(String[] args) throws Exception{Path path= Paths.get("love.txt");String info="I love three things in this worlds,the sun,the moon,and you.sun for morning, moon for night,and you for ever";Files.write(path,info.getBytes() );}很簡單的方法,但是這個方法最好不要操作大文件,因為write()方法是通過字節流來實現的。
write()方法源碼如下:
從上面的源碼可以看出,write()是通過OutputStream來實現寫入文件的.
使用Files.newBufferedWriter()來寫入文件
代碼如下:
public static void main(String[] args) {Path path = Paths.get("love.txt");try (BufferedWriter bw = Files.newBufferedWriter(path, Charset.forName("utf-8"))) {bw.write("浮世萬千,吾愛有三,日,月和你,日為朝,月為暮,卿為朝朝暮暮.");}catch (Exception e){e.printStackTrace();}}很容易就可以看出來,上面代碼是通過字符流來寫入文件的,通過Files.newBufferedWriter(path
, Charset.forName(“utf-8”))創建了字符流。
查看 newBufferedWriter()源碼:
使用Files.copy()來完成文件的復制
代碼如下:
public static void main(String[] args) {Path oldFile = Paths.get("love.txt");Path newFile = Paths.get("newLove.txt");try (OutputStream os = new FileOutputStream(newFile.toFile())) {Files.copy(oldFile, os);} catch (Exception e) {e.printStackTrace();}}很簡潔的方法,copy的源碼如下:
public static long copy(Path source, OutputStream out) throws IOException {// ensure not null before opening fileObjects.requireNonNull(out);try (InputStream in = newInputStream(source)) {return copy(in, out);}}可以看到獲取了老的文件的輸入流,繼續查看copy源碼:
private static long copy(InputStream source, OutputStream sink)throws IOException{long nread = 0L;byte[] buf = new byte[BUFFER_SIZE];int n;while ((n = source.read(buf)) > 0) {sink.write(buf, 0, n);nread += n;}return nread;}很明白了,通過老文件的輸入流讀取字節數組,通過新文件的輸出流將字節數組寫到新文件。
參考資料
1.Java Nio Write File Example
總結
以上是生活随笔為你收集整理的Java学习笔记 (二十七) 使用NIO写文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: adb和frida的一点简单使用记录
- 下一篇: 一起来DIY一个人工智能实验室吧