如何从input.txt文件创建String数组

时间:2015-10-05 21:33:52

标签: java arrays java.util.scanner stdin

我在创建一个从命令行读取参数的数组时遇到问题。该文件的第一行是整数N,该文件的其余部分包含每行的字符串。第一个整数是数组的大小。我已经成功分配了数组,但是我无法读取它来读取input.txt文件的整行。

以下是input.txt文件的示例:

4
hey, 03982
bye, 30980324
no, 3290823
yes, 30948432

以下是我的代码:

import java.util.Scanner;
import java.io.*;
import java.util.Arrays;

class databaseSearch{

public static void main( String[] args ){

    Scanner sc = null;

    // if no arguments are entered, print out 
    // error message and correct way to invoke program
    if(args.length == 0){
            errorMessage();
    }

// Try and open the first argument on the command line
    try{
        sc = new Scanner(new File(args[0]));
    }catch(FileNotFoundException e){
        System.err.println(e.getMessage());
        errorMessage();
    }


int arraySize = sc.nextInt();
sc.nextLine();
String[] DB = new String[arraySize];
for( int i = 0; i < arraySize; i++ ){
    DB[i] = sc.nextLine();
}



    System.out.println(Arrays.toString(DB));

}

// errorMessage()
// prints out an error message with correct with to invoke program
// terminates after instructions are given
static void errorMessage(){
    System.err.println("Please try again by running the program along with a correct file.");
    System.exit(1);
}
}

3 个答案:

答案 0 :(得分:0)

当您知道文件的结构时,您的外部while循环看起来不必要且危险。而是获取扫描程序,从文件中获取第一个int,使用该int创建数组,然后循环该数字,就是这样。

伪代码

get scanner for file
read in first int, call it arraySize. Note that nextInt() does not get the end of line token
get nextLine from scanner **and discard it** to handle the end of line token
create a String array arraySize length.
for int i goes from 0 to less than arraySize
   get a line from the Scanner
   put line in your String array
   //  Split the line using String split. // not sure if this needs to be done
end for loop
close scanner

旁注:您需要学习和使用Java命名约定,包括给出以小写字母开头的变量和方法名称,并给出以大写字母开头的类名。遵循这些规则将允许您创建其他人(我们!)可以更容易地遵循的代码。

如,

public static void main(String[] args) {
    if (args.length == 0) {
        // !! exit/error
    }

    String filePath = args[0];
    String[] lines = null;

    // use try with resources so that the resource, here the Scanner
    // gets closed when done being used.
    try (Scanner scan = new Scanner(new File(filePath))) {
        int arraySize = scan.nextInt();  // get first int
        scan.nextLine();  // swallow the end-of-line token
        lines = new String[arraySize];
        for (int i = 0; i < lines.length; i++) {
            lines[i] = scan.nextLine();
        }

        System.out.println("Display results:");
        for (String line : lines) {
            System.out.println(line);
        }
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
}

答案 1 :(得分:0)

使用Files.readAllLines().

List<String> lines = Files.readAllLines(Paths.get(arg[0]));
if (lines.isEmpty())
  throw new IllegalArgumentException("Empty file");
int count = Integer.parseInt(lines.remove(0)); 
if (lines.size() != count)
  throw new IllegalArgumentException("Incomplete file");
String[] db = lines.toArray(new String[count]);

答案 2 :(得分:-1)