阅读文件时的空白区域java
private Scanner inputFile;
private String corpusFileString = "";
try
{
File file = new File(sourceFile.getText());
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null, "The file was found.");
if (text != null)
{
translate.setEnabled(true);
}
}
catch (FileNotFoundException ex)
{
JOptionPane.showMessageDialog(null, "The file was not found.");
}
try
{
numberWords = inputFile.nextInt();
}
catch (InputMismatchException ex)
{
JOptionPane.showMessageDialog(null, "The first line on the file must be an integer");
}
while (inputFile.hasNext())
{
corpusFileString = corpusFileString + inputFile.nextLine() + " ";
}
所以当我读这个文件时,第一行应该是一个整数(一个不同的变量可以保存),否则会抛出一个异常。 该文件的其余部分应该是数据(所有数据的另一个变量),但由于某种原因,字符串在开始处包含空白区域,并且在分割它时,我必须在数组中使用+1来引起该空白区域。阅读文件时的空白区域java
问题是它读取第一个int,然后是第一行的其余部分。
基本上是:
15 \ n此行\ n这里
另一行,其中\ n是一个换行符。
它读取15,然后它读取到\ n,它是“”(省略换行符)。剩下的就是你所期望的。
尝试使用:
numberWords = Integer.parseInt(inputFile.nextLine());
而不是
numberWords = inputFile.nextInt();
使用String.Trim()删除字符串开头和结尾的空格。 链接到方法:http://msdn.microsoft.com/de-de/library/t97s7bs3(v=vs.110).aspx
问题是Java,而不是C#。这个问题与文件处理有关,我想。 – 2012-03-08 22:20:22
现在他已经改变了标签;-) – jwillmer 2012-03-08 22:22:55
我不知道关于Java。在尝试使用nextInt()
阅读之前,可能需要拨打hasNext()
。这就是.NET读者和统计员的工作方式。在C#中我会写类似
while (reader.MoveNext()) {
string s = reader.Current;
}
你的情况,你可以尝试
if (inputFile.hasNext()) {
numberWords = inputFile.nextInt();
}
这看起来更像是比Java C#。 – jrummell 2012-03-08 21:21:37
这似乎不是相关的代码部分。向我们展示'Scanner'类的代码。 – 2012-03-08 21:51:31
@ OlivierJacot-Descombes扫描仪是一个内置的Java类。 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html – 2012-03-08 22:15:04