我想使用分隔符"提取文件中的第一列,并将其保存到一个新文件中。输出生成此异常:
Exception in thread "main" java.lang.NullPointerException
at Extract.main(Extract.java:26)
这是我使用的代码,但我不确定它是否正确:
public class Extract {
public Extract(){
}
public static void main(String[] args) {
BufferedReader in = null;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/home/omar/Téléchargements/nursery.tmp"));
in = new BufferedReader(new FileReader("pima.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
if (splited.length > 0)
{
out.append(splited[0].toString());
out.newLine();
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
File f = new File("prima.txt");
f.delete();
File f2 = new File("pima.tmp");
f2.renameTo(new File("pima.txt"));
}
}
从while()
循环中删除第一行,即read = in.readLine();
。问题是,当您检查while条件时,您正在读取该行,而在while循环中,您正在再次读取一行(但这次是新行,因为readLine不仅读取一行,而且还将读取指针移动到下一行),因此您将获得下一行。
一旦超过文件末尾,就会得到null
而不是一行,这就是为什么会得到Exception。