java如何读取txt文件数据并把它存储到数组中

java如何读取txt文件数据并把它存储到数组中
例如txt中有以下数据

180.90 88
10.25 65
56.14 9
104.65 9
100.30 88
297.15 5
26.75 65
130.62 5
240.28 58
270.62 8
115.87 88
247.34 95
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class demo03  {
    static List x = new ArrayList();
    static List y = new ArrayList();

    public static void main(String args[]) {
        readFile();
    }

    /**
     * 读入TXT文件
     */
    public static void readFile() {
        String pathname = "C:\\Users\\Administrator\\Desktop\\01.txt"; // 绝对路径或相对路径都可以,写入文件时演示相对路径,读取以上路径的input.txt文件
        //防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw;
        //不关闭文件会导致资源的泄露,读写文件都同理
        //Java7的try-with-resources可以优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271
        try (FileReader reader = new FileReader(pathname);
             BufferedReader br = new BufferedReader(reader) // 建立一个对象,它把文件内容转成计算机能读懂的语言
        ) {
            String line;
            //网友推荐更加简洁的写法
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                String[] s =line.split(" ");
                x.add(s[0]);
                y.add(s[1]);
//                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
            System.out.println(x);
            System.out.println(y);
    }
}



发布了6 篇原创文章 · 获赞 0 · 访问量 167

猜你喜欢

转载自blog.csdn.net/qq_43568314/article/details/104315598