gpt4 book ai didi

java - 如何跳过文本文件的前 3 行?

转载 作者:行者123 更新时间:2023-12-01 06:33:47 28 4
gpt4 key购买 nike

当我使用Java读取文本文件时,如何跳过文本文件的前三行?

当前程序,

public class Reader {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt")));
Map<String, Integer> result = new LinkedHashMap<String, Integer>();
Map<String, Integer> result2 = new LinkedHashMap<String, Integer>();
while (reader.ready()) {
String line = reader.readLine();
//split a line with spaces
String[] values = line.split("\s+");
//set a key date\tanimal
String key = values[0] + "\t" + values[1];
int sum = 0;
int count = 0;
//get a last counter and sum
if (result.containsKey(key)) {
sum = result.get(key);
count = result2.get(key);
} else{

}
//increment sum a count and save in the map with key
result.put(key, sum + Integer.parseInt(values[2]));
result2.put(key, count + 1);
}

//interate and print new output
for (String key : result.keySet()) {
Integer sum = result.get(key);
Integer count = result2.get(key);
System.out.println(key + " " + sum + "\t" + count);
}
reader.close();
} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}
}

最佳答案

为什么你不能这样做?

//Skip 3 lines.
for(int i=1;i<=3;i++)
{
reader.readLine();
}

通过引入这两个类可以简化代码并使其更具可读性。那么你只能维护1个Map,

Map<Animal, Summary> result = new HashMap<Animal, Summary>();

class Animal
{
String date;

String name;

public Animal(final String date, final String n)
{
this.date = date;
this.name = n;
}

@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Animal))
{
return false;
}
Animal other = (Animal) obj;
if (date == null)
{
if (other.date != null)
{
return false;
}
}
else if (!date.equals(other.date))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
}

final static class Summary
{
private int total;

private int count;

void setTotal(int value)
{
total = value;
}

void setCount(int i)
{
count = i;
}

void increaseCount()
{
count++;
}

void addToTotal(int valueToAdd)
{
total += valueToAdd;
}
}

关于java - 如何跳过文本文件的前 3 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4533671/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com