Java讀按行讀文件內容

功能:使用Java讀取文件中的內容,按行讀取,並按照行內的空格將一行內容分割成若干個字符串。

import java.io.*;
/**
 * @Description: 讀行讀文件內容,並將一行內容按空格分隔
 * @Author: 詩人的情人
 * @Date: 2:45 下午 2019/10/16
 */

public class readFile {
    public static String[] parseLine(String str) {
        // split a string by space
        String[] res = str.split("\\s+");

        return res;

    }
    public static void main(String[] args) {
        try
        {
            String fileName = "/Users/admin/Desktop/fea.xml";
            File myFile = new File(fileName);
            if (myFile.isFile() && myFile.exists()) {
                System.out.println("file is exists");
                InputStreamReader read = new InputStreamReader(new FileInputStream(myFile));
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;

                while ((lineTxt = bufferedReader.readLine()) != null) {

                    String[] result = parseLine(lineTxt);
                    for (int i = 0; i < result.length; ++i) {
                        if (i == result.length - 1) {
                            System.out.print(result[i]);
                        } else {
                            System.out.print(result[i] + " ");
                        }
                    }
                    System.out.println();
                }
            } else {
                System.out.println("file is not exists!!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

測試文件爲:fea.xml
內容爲:在這裏插入圖片描述
輸出爲:

file is exists
李白 詩人
杜甫 詩人
白居易 詩人
李清照 詩人

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章