Java 这是我阅读文件的完整代码
请看一下从文本文件中逐行读取数据的代码Java 这是我阅读文件的完整代码,java,Java,请看一下从文本文件中逐行读取数据的代码 import java.util.Iterator; public class assignment { public static void main(String[] args) { In infile = new In(args[0]); String data = new String(); try { while((data = infile.readLine()) != n
import java.util.Iterator;
public class assignment {
public static void main(String[] args) {
In infile = new In(args[0]);
String data = new String();
try {
while((data = infile.readLine()) != null){
System.out.println(data);
}
} catch (NullPointerException e) {
}
}
}
这是课堂上的有向图,我把它去掉了
public final class In {
private Scanner scanner;
public In(String s) {
try {
// first try to read file from local file system
File file = new File(s);
lines = 0;
if (file.exists()) {
scanner = new Scanner(file, charsetName);
scanner.useLocale(usLocale);
while(scanner.hasNext()){
lines++;
}
return;
}
// next try for files included in jar
URL url = getClass().getResource(s);
// or URL from web
if (url == null) { url = new URL(s); }
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), charsetName);
scanner.useLocale(usLocale);
}
catch (IOException ioe) {
System.err.println("Could not open " + s);
}
}
下面是readline函数
public String readLine() {
String line;
try { line = scanner.nextLine(); }
catch (Exception e) { line = null; }
return line;
}
这是文本文件中的实际数据
13
15
2 3
0 6
0 1
2 0
11 12
9 12
9 10
9 11
3 5
8 7
5 4
0 5
6 4
6 9
7 6
这是控制台中的输出
13
13
0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
5 3
我不知道为什么它会重复和丢失值。
ReadLine()
函数调用
ReadNext()
函数即使我没有将readline转换为string(),但它仍然提供相同的输出为什么要对字符串调用
tostring()
,为什么在不需要的时候初始化数据?请注意,如果您不调用toString()
,则不需要捕获NullPointerException
——您不应该这样做。我们也不知道有向图和类中的有什么作用。最好先在那里关闭,然后转到下一个问题。此代码不完整