Fiz*_*ter 17 java file-io java.util.scanner
我正在用Java编写程序,我需要做的一件事是为最短路径问题创建一组每个有效位置.位置在.txt文件中定义,该文件遵循严格模式(每行一个条目,没有额外的空格),非常适合使用.nextLine来获取数据.我的问题是241行进入文件(432中)扫描仪停止工作3/4通过一个条目并且不识别任何新行.
我的代码:
//initialize state space
private static Set<String> posible(String posLoc) throws FileNotFoundException {
Scanner s = new Scanner(new File(posLoc));
Set<String> result = new TreeSet<String>();
String availalbe;
while(s.hasNextLine()) {
availalbe = s.nextLine();
result.add(availalbe);
}
s.close();
return result;
}
Run Code Online (Sandbox Code Playgroud)
数据
Shenlong Gundam
Altron Gundam
Tallgee[scanner stops reading here]se
Tallgeese II
Leo (Ground)
Leo (Space)
Run Code Online (Sandbox Code Playgroud)
当然,"扫描仪在此处停止读取"不在数据中,我只是标记扫描仪停止读取文件的位置.这是3068字节到文件中,但这不应该影响任何东西,因为在同一个程序中,几乎相同的代码,我正在读取编码路径的261行,14KB .txt文件.任何帮助,将不胜感激.
谢谢.
Hov*_*els 17
扫描仪读取文件时出现问题,但我不确定它是什么.它错误地认为它没有到达文件的末尾,可能是由于一些时髦的字符串编码.尝试使用包装FileReader对象的BufferedReader对象.
例如,
private static Set<String> posible2(String posLoc) {
Set<String> result = new TreeSet<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(posLoc)));
String availalbe;
while((availalbe = br.readLine()) != null) {
result.add(availalbe);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
编辑
我尝试将问题减少到最低限度,这足以引出问题:
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File(FILE_POS));
int count = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.printf("%3d: %s %n", count, line );
count++;
}
Run Code Online (Sandbox Code Playgroud)
我用printf检查了Scanner对象:
System.out.printf("Str: %-35s size%5d; Has next line? %b%n", availalbe, result.size(), s.hasNextLine());
Run Code Online (Sandbox Code Playgroud)
并表明它认为该文件已经结束.我正在逐步删除从数据到文件的行,以查看导致问题的行,但是会留给您.
小智 7
我遇到了同样的问题,这就是我所做的修复它:
1.Saved the file I was reading from into UTF-8
2.Created new Scanner like below, specifying the encoding type:
Scanner scanner = new Scanner(new File("C:/IDSBRIEF/GuidData/"+sFileName),"UTF-8");
Run Code Online (Sandbox Code Playgroud)
小智 5
我遇到了同样的问题.扫描仪不会读到文件的末尾,实际上是在一个单词的中间停止.我认为这是一个问题,扫描仪设置了一些限制,但我注意到rfeak关于字符编码的评论.
我重新保存了.txt我正在阅读的内容UTF-8,它解决了问题.事实证明,Notepad默认为ANSI.