天天看點

gava實作文本内容讀取以及寫入

代碼功能:

   Java實作文本内容讀取以及寫入,兩者結合可以實作檔案的拷貝。供學習的朋友參考。

工具:IntelliJ IDEA

文本内容讀取代碼如下:

package testIO;

import java.io.*;
/**
 * 功能:實作從E:/a.txt中讀取文本内容
 * 編碼:
 * GBK:中文占2個位元組
 * UTF-8:中文占3個位元組
 * BufferedReader:建立一個使用預設大小輸入緩沖區的緩沖字元輸入流
 * InputStreamReader:将位元組流轉換為字元流處理。轉換流,是位元組流和字元流之間的橋梁
 * Created by Administrator on 2017/9/23.
 */
public class TestBR {
    public static void main(String[] args) {
        String result  =getFile(new File("E:/a.txt"));
        System.out.println(result);
    }

    public static String getFile(File file) {
        InputStreamReader isr = null;
        FileInputStream fis = null;
        BufferedReader br = null;
        StringBuilder sb=new StringBuilder();
        try {
            fis = new FileInputStream(file);//基本流
            isr = new InputStreamReader(fis, "utf-8");//可以一次讀取一個中文字元
            br = new BufferedReader(isr);//建立一個使用預設大小輸入緩沖區的緩沖字元輸入流
            String str = null;
            while ((str = br.readLine()) != null) {//一讀讀一行
                sb.append(str);
                //  sb.append("\r\n");設定輸出分行
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}



           

文本内容寫入 代碼如下:

package testIO;

import java.io.*;

/**功能:實作把文本内容寫入到E:/a.txt檔案中
 * PrintWriter:一寫,寫一行字元
 * Created by Administrator on 2017/9/23.
 */
public class TestPrintWriter {
    public static void main(String[] args) {
        PrintWriter pw=null ;
        try {
            pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File("E:/a.txt"),false),"utf-8"));//預設false檔案覆寫,true表示後面添加,不覆寫已有内容
            pw.println("測試");
            pw.println("gava學習");
            pw.println("測試");
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            if(pw!=null)
            {
                pw.close();
            }
        }

    }
}
           

繼續閱讀