这里我正在读取每行中包含整数的文本文件,并且打印出现多次出现的所有整数。从文本文件中读取时的数字格式异常
正如你所看到的我使用哈希映射和我分配整数作为键和数量作为值的出现次数。
这里我在这里得到数字格式异常。谁能帮我这个?
package fileread;
import java.io.*;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
HashMap<Integer, Integer> lines = new HashMap<Integer, Integer>();
try {
FileInputStream fstream = new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
Integer intObj = Integer.valueOf(str);
if (lines.containsKey(intObj)) {
int x = 0;
x = lines.get(intObj);
if (x == 2) {
System.out.println(intObj);
}
lines.put(intObj, x++);
} else {
lines.put(intObj, 1);
}
}
in.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
异常消息将显示它试图解析为整数。 – hmjd
'DataInputStream'是必需的吗?那可能会导致这个问题? –
@ nicholas.hauschild是的,DataInputStream似乎没有必要。你应该能够将'fstream'直接传递给'BufferedReader'构造函数。 –