JAVA文件讀寫操作


一、讀文件 BufferedInputStream 

BufferedInputStream必須傳入一個InputStream(一般是FileInputStream)

常用方法:

//從該輸入流中讀取一個字節 public int read();

//從此字節輸入流中給定偏移量處開始將各字節讀取到指定的 byte 數組中。

public int read(byte[] b,int off,int len)

應用實例:

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 * BufferedInputStream:緩沖輸入流
 * FileInputStream:文件輸入流
 */
public class FileReadToString {
    public static void main(String[] args){
        try {
            FileInputStream fis=new FileInputStream("WynnNi.txt");
            BufferedInputStream bis=new BufferedInputStream(fis);
            String content=null;
             //自定義緩沖區
            byte[] buffer=new byte[10240];
            int flag=0;
            while((flag=bis.read(buffer))!=-1){
                content+=new String(buffer, 0, flag);
            }
            System.out.println(content);
            //關閉的時候只需要關閉最外層的流就行了
            bis.close();
        } catch (Exception e) {
                e.printStackTrace();
        }
    }
}

二、寫文件  BufferedOutputStream

創建一個新的緩沖輸出流,以將數據寫入指定的底層輸出流。

常用方法:

//向輸出流中輸出一個字節
public void write(int b);

//將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此緩沖的輸出流。
public void write(byte[] b,int off,int len);

//刷新此緩沖的輸出流。這迫使所有緩沖的輸出字節被寫出到底層輸出流中。
public void flush();

應用實例

/**
 * BufferedOutputStream:緩沖輸出流
 * FileOutPutStream:文件輸出流
 */
public class StringOutPutToFile {
    public static void main(String[] args){
        try {
            FileOutputStream fos=new FileOutputStream("WynnNi.txt");
            BufferedOutputStream bos=new BufferedOutputStream(fos);
            String content="xxxxxxxxx!";
            bos.write(content.getBytes(),0,content.getBytes().length);
            bos.flush();
            bos.close();
        } catch (Exception e) {
                e.printStackTrace();
        }
    }
}

三、實際應用場景

被調用方如何將文件傳輸給調用方並在本地輸出文件

1、被調用方將文件讀入緩沖區byte[]

2、將緩沖區數據轉換成String傳遞,String str = Base64.getEncoder().encodeToString(bytes);

3、接收方將String反轉為byte[],bytes=Base64.getDecoder().decode(str);

4、接收方將緩沖區輸出到文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM