对于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& 4s: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]);
}
答案 0 :(得分: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);
}