假设有一个文件 test.csv,有一个表:
Name Age Count
Bob 25 4
Sam 45 5
问题是,要编写什么代码,以便在读取流时跳过第一行Name;Age;Count并立即从第二行开始Bob;25;4?
这是代码:
public class CSVtestclass {
public static void main(String[] args) throws IOException {
String FileName = "c:\\TestJava\\test.csv";
File file = new File(FileName);
Map<String, WordInfo> wordInfoMap = new HashMap<>();
try(BufferedReader read = new BufferedReader(new FileReader(file))){
String s;
String wordName;
HashMap<String, int[]> stringIntegerHashMap = new HashMap<>();
while( (s = read.readLine()) != null) {
String[] next = s.split(";");
wordName = next[0];
if (stringIntegerHashMap.containsKey(wordName)) {
int[] ints = stringIntegerHashMap.get(wordName);
ints[0]++;
ints[1] += Integer.parseInt(next[3]);
} else {
stringIntegerHashMap.put(wordName, new int[]{1, Integer.parseInt(next[3])});
}
}
for (Map.Entry<String, int[]> pair: stringIntegerHashMap.entrySet()) {
int[] value = pair.getValue();
System.out.printf("%s zayavki: %d interakcii: %d%n", pair.getKey(), value[0], value[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
如果总是需要它,只需
readLine在读取循环之前插入一个 1 即可。如果您不需要总是和不同的行数,那么编写一个单独的方法来跳过行。
如果您确切知道要跳过的字符数,则可以使用
Reader.skip(long n)如果您需要的行彼此相似,那么您可以尝试切断不必要的正则表达式。