关于FileReader代码

问题描述 投票:-3回答:1

对于FileReader的代码片段,我很陌生,编写器更简单。但问题是,当涉及到FileReader时,我需要读取.txt文件并显示文本文件中的特定数据。

.txt文件的格式如下:

01 Jan 2018     1     2     12     Y     NS213B     515     N Summers

                      ^
                      |

我需要第三列数据只有3和4,并将其放入变量。所以它会显示出类似的东西

System.out.println("Total number of 3 & 4s: " + numberOf3N4s);  

输出将显示如下:总数3和4:100

public static void displaySummaryofContracts()
{   
    String filePath = "contracts.txt";  //Change to either contracts.txt or archive.txt, only accesible files
    int numberOfContracts = 0;
    String arr[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    String space = "   ";

    try {
        try (BufferedReader lineReader = new BufferedReader(new FileReader(filePath)))
        {
            String lineText = null;

            while ((lineText = lineReader.readLine()) != null) {
                numberOfContracts++;
            }
        }
    } 
    catch (IOException ex)
    {
        System.err.println(ex);
    }

    System.out.println("Total Number of Contracts: " + numberOfContracts);
    System.out.println("Number of contracts per Month:");
    System.out.println(arr[0] + space + arr[1] + space + arr[2] + space + arr[3] + space + arr[4]  + space + arr[5]  
             + space + arr[6] + space + arr[7] + space + arr[8] + space + arr[9] + space + arr[10] + space + arr[11]);
}
java
1个回答
1
投票

根据你的陈述,你需要第3栏。对于文件中的每一行,将行拆分为字符串数组,使用制表符作为deliter。在检索到的数组中使用第二个元素或验证。 try-catch语句可以写成如下:

    ArrayList<String> savedLines = new ArrayList<String>();
    try (BufferedReader lineReader = new BufferedReader(new FileReader(filePath)))
    {
        String lineText = null;

        while ((lineText = lineReader.readLine()) != null) {
            String[] split = lineText.split("\t"); 
            if(split[2].equals("3")||split[2].equals("4")){
                    savedLines.add(lineText);
                    numberOfContracts++;
            }


        }
    } 
    catch (IOException ex)
    {
        System.err.println(ex);
    }
© www.soinside.com 2019 - 2024. All rights reserved.