[英]JAVA - Simple File Reader (classes: File, Scanner, hasNextLine()) - compiled, but not work
I have a little problem. 我有一点问题。 I am using NetBeans, and I want to create a program, which will exchange characters in *.csv file.
我正在使用NetBeans,并且想创建一个程序,该程序将交换* .csv文件中的字符。
I was trying to load file on few ways, but I do not now why, it do not works 我试图以几种方式加载文件,但是我现在不为什么,它不起作用
Code is correct, it can be compiled: 代码正确,可以编译:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FixRaports {
public static void main(String[] args) throws FileNotFoundException {
String filePath = "D:/ala.csv";
File fileName = new File(filePath);
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine())
{
line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
Of course, file "ala.csv" is existing on D:\\ . 当然,文件“ ala.csv”存在于D:\\上。
It contains: 它包含:
Ja "lubie " - placki
bo placki są fajne i "slitasne"
""" My tez je lubimy """
- odpowie ci 'prawie' każdy
"placki ; placki ; ' to jest; to ! """
The code is correctly compiled, but when i play application, it only returns: 该代码已正确编译,但是当我播放应用程序时,它仅返回:
run:
BUILD SUCCESSFUL (total time: 0 seconds)
So I tried : 所以我尝试了:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FixRaports {
public static void main(String[] args) throws FileNotFoundException {
String filePath = "D:/ala.txt";
File fileName = new File(filePath);
Scanner scanner = new Scanner(fileName);
String line = scanner.nextLine();
System.out.println(line);
scanner.close();
}
}
And the it returns: 它返回:
run:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at FixRaports.main(FixRaports.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I do not understand, why NetBeans returns "No line found" , when file "ala.csv" contains a few lines? 我不明白,当文件“ ala.csv”包含几行时,为什么NetBeans返回“找不到行”?
What I am doing wrong? 我做错了什么?
Your first code doesn't compile: the line 您的第一个代码无法编译:
line = scanner.nextLine();
can't work because the variable line is undefined. 由于变量行未定义而无法工作。 Replace it with
替换为
String line = scanner.nextLine();
as you did in the second example and the code is correct. 就像您在第二个示例中所做的那样,代码是正确的。
As to why the scanner doesn't return a line: the NoSuchElementException is thrown when the scanner doesn't find the desired token (in your case a newline). 关于扫描器为什么不返回行的原因:当扫描器找不到所需的令牌(在您的情况下为换行符)时,将引发NoSuchElementException。 Please examine your file if it contains a newline.
请检查您的文件是否包含换行符。
Last, please note that in your question you're referring to ala.csv, but in your code you open the file ala.txt.Perhaps you just created a new file which of course doesn't contain a newline. 最后,请注意在您的问题中您指的是ala.csv,但是在您的代码中打开了文件ala.txt。也许您只是创建了一个新文件,当然其中不包含换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.