按行读取txt文件内容并截取字符串

要求:按行读取文本文档中的内容 ,并截取相关内容显示在控制台

文档内容:

以第一行为例,需要输出:69 62 000144

1、新建module

2、在src目录下新建class文件

代码如下

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

/**
 * @author cyz
 * @date 2019/3/21 15:48
 */
public class Sub {
    /**
     * @author cyz
     * @description 按行读取文件
     */
    public static List read() throws FileNotFoundException {
        // 文件所在位置
        File file = new File("E:/A.txt");
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(fis,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder stringBuilder =new StringBuilder();
        List<String> strings =new ArrayList<>();
        String str=null;
        while (true) {
            try {
                if (!((str=bufferedReader.readLine())!=null)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (str.trim().length()>2) {
                strings.add(str);
            }
        }
        return strings;
    }

    public void test() throws Exception {
        List list = read();
        for (int i=0;i<list.size();i++){
            //list.get(i)中存储的是object对象,加.toString()转为string对象
            String str = list.get(i).toString();
            //字符串截取str.substring(2,4)表示从第二个以后截取,到第四个结束,就是截取3,4位置的字符
            String str1= str.substring(2,4);
            String str2= str.substring(5,7);
            String str3= str.substring(10,16);
            System.out.println(str1+"\t"+str2+"\t"+str3);
        }
    }

    //mian函数调用类函数
    public static void main(String[] args) throws Exception {
        Sub sub = new Sub();
        sub.test();
    }
}

3、执行main方法

控制台输出:

总结:

(1)list中存放的是object对象,需要转为string

(2)str.substring(2,4)表示从第二个以后截取,到第四个结束。就是截取3,4位置的字符。

(3)要执行单个java,必须要有mian方法,我捣鼓了 半天,想吃了屎一样,菜啊

 

猜你喜欢

转载自blog.csdn.net/weixin_43163261/article/details/88717999
今日推荐