1. 程式人生 > >java 使用 NIO 讀寫檔案

java 使用 NIO 讀寫檔案

    public static void Readnio() {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile("f:\\a.txt", "rw");		//字元檔案
           // randomAccessFile = new RandomAccessFile("f:\\a.jpg", "rw");	//位元組檔案
            fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = fileChannel.read(byteBuffer);
            while (read != -1) {
                byteBuffer.flip();	// Buffer切換為讀取模式
                while (byteBuffer.hasRemaining()) {
                    System.out.println((char) byteBuffer.get());
					WriteNio(String.valueOf((char) byteBuffer.get()), null);	//寫入字元
				//	WriteNio(null, buf);			//寫入位元組
                }
                byteBuffer.compact();      // 清空Buffer區
                read = fileChannel.read(byteBuffer);     // 繼續將資料寫入快取區
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
public static void WriteNio(String str, ByteBuffer byteBuffer) {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile("f:\\b.txt", "rw");		//字元檔案
         //  randomAccessFile = new RandomAccessFile("f:\\b.jpg", "rw");	//位元組檔案
            randomAccessFile.seek(randomAccessFile.length());           //防止覆蓋原檔案內容
            fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer1 = ByteBuffer.wrap(str.getBytes());
            fileChannel.write(byteBuffer1);	 //寫入字元            
         //   fileChannel.write(byteBuffer);	//寫入位元組

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();

                }
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }