簡體   English   中英

逐行讀取Java

[英]Read line by line java

我有一個看起來像這樣的文本文件:

1 
2 3
4 5
6 7

我想有2個字符串,它們是同一行的值。 例:

字符串s1將為2,字符串s2將為3

我這樣嘗試過:

    File file = new File("e:\\read.txt");
    if (file.exists()){
     FileReader fr = new FileReader(file);
     LineNumberReader ln = new LineNumberReader(fr);
        while (ln.getLineNumber() == 0){

            s=Integer.parseInt(ln.readLine());
         System.out.println(s);
        }
        DisjointSetLinkedList dsj=new DisjointSetLinkedList();
        while(ln.getLineNumber()>0)
        {

           String [] tokens = ln.readLine().split(" ");
           s1=tokens[0];
           System.out.println( s1);
        }

我必須在同一行的2個字符串之間建立並集:

將第二個循環更改為:

    String line = null;
    while ((line = ln.readLine()) != null) {

        String[] tokens = line.split(" ");
        String s1 = tokens[0];
        String s2 = tokens[1];
        System.out.println("s1 = " + s1 + " s2 = " + s2);
    }

否則,當嘗試訪問使用ln.readLine()讀取的最后一行時,將出現NullPointerException

您也不需要while loop來讀取第一行,只需讀取一次即可。

我認為這樣更容易:

    try {
        File file = new File("numbers.txt");
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine())!= null) {
            String[] tokens = line.split("\\s");
            System.out.println(Arrays.toString(tokens));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

如果您將token [0]作為整個第一行,則可以像這樣進行合並

for(int i=2; i<token.length;i+2)
   System.out.println("UNION: "+Union(token[i-2], token[i]));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM