【问题标题】:Array size based on the file being read基于正在读取的文件的数组大小
【发布时间】:2014-05-11 02:47:18
【问题描述】:

我试图将我的数组大小基于从文本文件中读取的行数,该文本文件的行数未知。我尝试读取文件两次,第一次使用 while 循环并递增 int,然后将其用于数组大小,但这似乎不起作用。然后我尝试将行的值放入列表中并获取列表大小,但这也不起作用。任何帮助都会很棒。

第一次使用 int 来递增。我什么也没得到。

import java.io.*;

import java.util.*;

public class Scan {

public static void main(String args[]) throws IOException {
    String routeName = " ";
    String stationName = " ";
    Scanner timetable = new Scanner(new File("fileName.txt"));
    int i = 0;
    while(timetable.hasNext()){ 
    i++;
    }
    int count = 0;
    String [] s = new String[i];
    while (timetable.hasNext()) {
        String line = timetable.nextLine();
        s[count++] = line;      
    }
    routeName = s[0];
    stationName = s[1];
    System.out.println(routeName.toString());
    System.out.println(stationName.toString());         
}

}

第二次使用列表。我得到一个 NullPointerException。

import java.io.*;

import java.util.*;

public class Scan {

public static void main(String args[]) throws IOException {
    String routeName = " ";
    String stationName = " ";
    Scanner timetable = new Scanner(new File("fileName.txt"));
    List<String> list = new ArrayList<String>();
    while(timetable.hasNext()){ 
    list.add(timetable.next);
    }
    int i = list.size(); 
    int count = 0;
    String [] s = new String[i];
    while (timetable.hasNext()) {
        String line = timetable.nextLine();
        s[count++] = line;      
    }
    routeName = s[0];
    stationName = s[1];
    System.out.println(routeName.toString());
    System.out.println(stationName.toString());         
}

}

【问题讨论】:

  • 需要使用数组吗?为什么不使用List

标签: java arrays


【解决方案1】:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadFile {
    public static void main(String[] args) {
        String fileName = "path";


        try {
            List<String> lines = Files.readAllLines(Paths.get(fileName),
                    Charset.defaultCharset());
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

虽然它会存储在 List 中,而不是数组。但会为你的目的工作。请注意,它适用于 java 7。

【讨论】:

    【解决方案2】:

    如上所述,最好使用List。但除此之外,您的代码中还有一个错误。您必须在第二个 while 语句之前再次重置时间表变量。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2016-02-17
      • 2023-01-28
      • 2021-09-03
      相关资源
      最近更新 更多