Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这是我阅读文件的完整代码_Java - Fatal编程技术网

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
——您不应该这样做。我们也不知道
有向图和
类中的
有什么作用。最好先在那里关闭,然后转到下一个问题。此代码不完整