java讀取本地文件內容-TXT文件


 

本地新建多個文本並分別寫入內容,如下:

 

 

代碼:

package com.test.controller;

import java.io.*;

/**
 * 報文批量推送
 *
 * @author liuwenlong
 * @create 2021-11-30 21:01:26
 */
@SuppressWarnings("all")
public class BatchPacketPush {


    public static void main(String[] args) {
        try {

            //獲取絕對路徑下的文件
            for (int i = 1; i <= 3; i++) {
                String s1 = BatchPacketPush.readTxt(new File("D:\\報文推送\\" + i + ".txt"));
                System.out.println(s1);
                Thread.sleep(5000);  //5000毫秒就是5秒
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 讀文件
     *
     * @param file 文件
     * @return
     * @throws IOException
     * @throws IOException
     */
    public static String readTxt(File file) throws IOException, IOException {
        String s = "";
        InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
        BufferedReader br = new BufferedReader(in);
        StringBuffer content = new StringBuffer();
        while ((s = br.readLine()) != null) {
            content = content.append(s);
        }
        return content.toString();
    }
}

運行效果

 


免責聲明!

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



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