IO流讀取和寫入文件


package com.xmlmysql.demo.config;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class TxtUtil {
    /**
     *  讀取文件
     * @param path
     * @return 文件的字符串內容
     */
    public static String test(String path) {
        try {
            String pathname = path;
            // File對象
            File filename = new File(pathname);
            // 文件字節輸入流對象
            FileInputStream fileInputStream = new FileInputStream(filename);
            // 字節轉字符輸入流對象 InputStreamReader:字節流到字符流的橋梁
            InputStreamReader reader = new InputStreamReader(fileInputStream, "GBK");
            // BufferedReader(字符緩沖輸入流),提供通用的緩沖方式文本讀取
            BufferedReader br = new BufferedReader(reader);
            // 多線程StringBuffer 單線程StringBuilder
            StringBuffer txt = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {

                txt.append(line+";");
            }
            // 方法一:流的關閉:先打開的后關閉,后打開的先關閉
            // 方法二:可以只調用外層流的close方法關閉其裝飾的內層流
            br.close();
            return txt.toString();
        } catch (Exception e) {
            // e.printStackTrace();
            return null;
        }
    }

    /**
     * 寫入Txt
     * @param path
     * @param txt
     * @throws IOException
     */
    public static boolean writeFile(String path, String txt) {
        // 相對路徑,如果沒有則要建立一個新的path文件
        File file = new File(path);
        try {
            // 創建新文件
            file.createNewFile();
            // 字符緩沖輸出流:寫東西到該文件
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            // 寫東西:\r\n即為換行
            out.write(txt);
            // 把緩存區內容壓入文件
            out.flush();
            // 最后關閉流
            out.close();
            //返回成功
            return true;
        } catch (IOException e) {
            //e.printStackTrace();
            //返回失敗
            return false;
        }
    }

}

 


免責聲明!

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



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