1. 程式人生 > 程式設計 >java讀取txt檔案並輸出結果

java讀取txt檔案並輸出結果

這篇文章主要介紹了java讀取txt檔案並輸出結果,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

描述:

1.java讀取指定txt檔案並解析

檔案格式:

程式碼:

package com.thinkgem.wlw.modules.midea;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhouhe
 * @Date: 2019/6/19 8:48
 */
public class Test {
  public static void main(String[] args) {
    // 資料夾路徑
    String path = "D:\\input.txt";
    try {
      List<String> scanListPath = readFile02(path);
//      System.out.println(scanListPath);
      for (int i = 0; i < scanListPath.size(); i++) {
        String mytext = scanListPath.get(i);

        //替換所有制表符
        mytext = mytext.replaceAll("\t",",");
        System.out.println(mytext);
        //每一行都轉化為新的陣列,根據下標去判斷引數值對應的引數是什麼
        String [] strArr= mytext.split(","); //注意分隔符是需要轉譯
        for (int m = 0; m < strArr.length; m++) {
//          System.out.println(strArr[m]);
          switch(m){
            case 0:
              System.out.println("時間:"+strArr[m]);
              break;
            case 1:
              System.out.println("甲烷:"+strArr[m]);
              break;
            case 2:
              System.out.println("總烴:"+strArr[m]);
              break;
            case 3:
              System.out.println("非甲烷總烴:"+strArr[m]);
              break;
            case 4:
              System.out.println("氨氣:"+strArr[m]);
              break;
            case 5:
              System.out.println("硫化氫:"+strArr[m]);
              break;
            case 6:
              System.out.println("氧氣:"+strArr[m]);
              break;
            default:
              break;
          }
        }
      }
    } catch (IOException e) {
      System.out.println("有異常,無法讀取!!!");
    }
  }

  /**
   * 讀取一個文字 一行一行讀取
   *
   * @param path
   * @return
   * @throws IOException
   */
  public static List<String> readFile02(String path) throws IOException {
    // 使用一個字串集合來儲存文字中的路徑 ,也可用String []陣列
    List<String> list = new ArrayList<String>();
    FileInputStream fis = new FileInputStream(path);
    // 防止路徑亂碼  如果utf-8 亂碼 改GBK   eclipse裡建立的txt 用UTF-8,在電腦上自己建立的txt 用GBK
    InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = "";
    while ((line = br.readLine()) != null) {
      // 如果 t x t檔案裡的路徑 不包含---字串    這裡是對裡面的內容進行一個篩選
      if (line.lastIndexOf("---") < 0) {
        list.add(line);
      }
    }
    br.close();
    isr.close();
    fis.close();
    return list;
  }
}

結果:

2.java讀取指定資料夾下的所有txt檔案並輸出內容(我這裡一個資料夾下面有 2 個txt檔案):

程式碼:

package com.thinkgem.wlw.modules.midea;

import java.io.*;

/**
 * @Author zhouhe
 * @Date 2019/10/10 13:10
 */
public class Test2 {


  /**新建一個類把下面程式碼放進去,注意要設定basePath(你要讀取的資料夾),讀取和寫入的方法也都寫好了.你可以根據自己的需求掉用就行了**/
  static String basePath="D:\\測試";
  /**
   * 查詢資料夾下所有符合csv的檔案
   *
   * @param dir 要查詢的資料夾物件
   * */
  public static void findFile(File dir) throws IOException {
    File[] dirFiles = dir.listFiles();
    for(File temp : dirFiles){
      if(!temp.isFile()){
        findFile(temp);
      }
    //查詢指定的檔案
    if(temp.isFile() && temp.getAbsolutePath().endsWith(".txt") ){
        //獲取檔案路徑,包含檔名
        String filePath = temp.getAbsolutePath();
        //獲取檔名
        String fileName = temp.getName();
        System.out.println(temp.isFile() + " " + temp.getAbsolutePath());
    readFileContent(temp);
    }
    }
  }

  /**
   * @param file 要讀取的檔案物件
   * @return 返回檔案的內容
   * */
  public static String readFileContent(File file) throws IOException{
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    StringBuffer sb = new StringBuffer();
    while(br.ready()){
//      sb.append(br.readLine());
      System.out.println(br.readLine());
    }
    System.out.println(sb.toString());
    return sb.toString();
  }

  /**
   * @param file 要寫入的檔案物件
   * @param content 要寫入的檔案內容
   * */
  public static void writeFileContent(File file,String content) throws IOException{
    FileWriter fw = new FileWriter(file);
    fw.write(content);
    fw.flush();
    fw.close();
  }

  public static void main(String[] args) {
    try {
      findFile(new File(basePath));
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
  }
}

結果:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。