用BufferedReader解析文件

我想了解更多有关使用文件(更一般地说是使用字符串)的信息。

为此,我使用以下输入创建了一个自定义.txt文件:

Function            Time
print()             0:32
find()              0:40
insert()            1:34

我想解析该文件并汇总已激活了多少“功能”。另外,我想汇总此操作所花费的总时间(即(0.32 + 0.4 + 1.34)/0.6 = 2:46分钟)

对于上述数据,输出应为:

3 functions in total time of 2:46 minutes

对于该解决方案,我显然创建了BufferedReader并逐行解析,但是有很多空格,并且使用这种输入不是很好。我希望有人能建议我使用这种数据的正确方法。

我也很感谢与此类练习的任何链接,因为我正试图找到一份工作,他们会问有关解析此类数据(字符串和文件)的许多问题。

感谢您的帮助! :)

xaut2008 回答:用BufferedReader解析文件

一般来说,您应该逐行处理文件。对于每行,您可以使用split函数将行分成几部分(从StringString[])。注意,split函数的参数是用于分割原始文本的字符或正则表达式。例如,使用str.split("\\s+")将拆分输入文本,将多个空格视为一个空格。另外,您可以使用trim函数删除不需要的空格,端线,制表符等,然后正确地解析信息。

关于解析时间值的细节,Java有一些内置的类和方法来处理本地日期,经过的时间等(例如LocalTimeCalendar)。但是,在我的示例中,我建立了一个自定义FuncTime类来使事情变得简单。

代码如下:

package fileParser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


public class FileParser {

    private static class FuncTime {

        private int seconds;
        private int minutes;


        public FuncTime() {
            this.seconds = 0;
            this.minutes = 0;

        }

        public FuncTime(int seconds,int minutes) {
            this.seconds = seconds;
            this.minutes = minutes;
        }

        public void accumulate(FuncTime ft) {
            this.seconds += ft.seconds;
            while (this.seconds >= 60) {
                this.seconds -= 60;
                this.minutes += 1;
            }
            this.minutes += ft.minutes;
        }

        @Override
        public String toString() {
            return this.minutes + ":" + this.seconds;
        }
    }


    private static void parseInfo(String fileName) {
        // Create structure to store parsed data
        Map<String,FuncTime> data = new HashMap<>();

        // Parse data from file
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            // Skip header (DATA FILE MUST ALWAYS CONTAIN HEADER)
            String line = reader.readLine();
            // Begin to process from 2nd line
            line = reader.readLine();
            while (line != null) {
                // Split funcName and time
                String[] lineInfo = line.split("\\s+");
                String funcName = lineInfo[0].trim();
                // Split time in minutes and seconds
                String[] timeInfo = lineInfo[1].split(":");
                int seconds = Integer.valueOf(timeInfo[1].trim());
                int minutes = Integer.valueOf(timeInfo[0].trim());

                // Store the function name and its times
                FuncTime ft = new FuncTime(seconds,minutes);
                data.put(funcName,ft);

                // Read next line
                line = reader.readLine();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        // Print parsed information
        FuncTime totalTime = new FuncTime();
        for (Entry<String,FuncTime> entry : data.entrySet()) {
            String funcName = entry.getKey();
            FuncTime ft = entry.getValue();
            System.out.println(funcName + " " + ft);
            totalTime.accumulate(ft);
        }
        // Print total
        System.out.println(data.size() + " functions in total time of " + totalTime);
    }

    public static void main(String[] args) {
        String fileName = args[0];

        parseInfo(fileName);
    }

}

您可以将提供的示例数据存储在名为example.data的文件中:

$ more example.data
Function            Time
print()             0:32
find()              0:40
insert()            1:34

并运行上面的代码,获得以下输出:

insert() 1:34
print() 0:32
find() 0:40
3 functions in total time of 2:46
,

您的意思是这样的吗?

int count = 0;
int totalMinutes = 0;
int totalSeconds = 0;
try (BufferedReader in = Files.newBufferedReader(Paths.get("test.txt"))) {
    Pattern p = Pattern.compile("(\\S+)\\s+(\\d+):(\\d+)");
    for (String line; (line = in.readLine()) != null; ) {
        Matcher m = p.matcher(line);
        if (m.matches()) {
            // not used: String function = m.group(1);
            int minutes = Integer.parseInt(m.group(2));
            int seconds = Integer.parseInt(m.group(3));
            count++;
            totalMinutes += minutes;
            totalSeconds += seconds;
        }
    }
}
if (count == 0) {
    System.out.println("No functions found");
} else {
    totalMinutes += totalSeconds / 60;
    totalSeconds %= 60;
    System.out.printf("%d functions in total time of %d minutes %d seconds%n",count,totalMinutes,totalSeconds);
}

输出

3 functions in total time of 2 minutes 46 seconds
本文链接:https://www.f2er.com/3166323.html

大家都在问