我试图用扫描仪类读取名为“test.txt”的文本文件。在txt文件中,它只是一句话:“这是一个txt文件”。这句话就是我想要写出来的。但是当我使用命令时,我写出来的就是txt文件的名称:java UDPClient test.txt localhost。
任何人都可以在代码中看到错误,这样我才能做对吗?我有两个可能的代码。
Import java.net.*;
Import java.io.*;
Import java.util.*;
public class Test_scanner {
public String readFile(String fileName) throws IOException {
File file = new File("test.txt");
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner s = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while (s.hasNextLine()) {
fileContents.append(s.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
s.close();
}
}
}
我也有这段代码:
import java.net.*;
import java.io.*;
import java.util.*;
public class Test_scanner {
public static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
导入语句中的“import”不应该大写,因此您的第二个代码块正确。我在两个代码中都没有看到main()方法;你需要一个main()方法来运行你的程序。假设您使用命令行输入文件名,可以使用以下内容:
import.java.io.*;
import.java.util.*;
public class TestScanner{
public static void main(String[] args) {
String sFileName = "";
//checks if user enters a file name
if(args.length == 0) {
System.out.println("Please enter a file name in command line.");
//terminates program
System.exit(0);
}
else {
sFileName = args[0];
}
File myFile = new File(sFileName);
//scanner object which reads from file
Scanner fileReader = null;
try {
//links scanner object to file.
fileReader = new Scanner(myFile);
}
catch (FileNotFoundException fnf) {
System.out.println("ERROR: File not found for " + sFileName);
//terminates program
System.exit(1);
}
System.out.println("Reading from file: " + sFileName + "\n");
//fileReader reads each line from file.
while(fileReader.hasNextLine()) {
//stores each line from file trimmed
System.out.println(fileReader.nextLine());
}
}//end main() method
}//end TestScanner class