如何从文件读取到数组

nna*_*nna 0 java arrays file-io

我正在尝试从文件读取数组.我尝试了两种不同的风格,两种都不起作用.以下是两种风格.

风格1

public class FileRead {

        int i;
        String a[] = new String[2];
        public void read() throws FileNotFoundException {
            //Z means: "The end of the input but for the final terminator, if any"

            a[i] = new Scanner(new File("C:\\Users\\nnanna\\Documents\\login.txt")).useDelimiter("\\n").next();
           for(i=0; i<=a.length; i++){
            System.out.println("" + a[i]);
           }


        }

        public static void main(String args[]) throws FileNotFoundException{
            new FileRead().read();

        }
    }
Run Code Online (Sandbox Code Playgroud)

风格2

public class FileReadExample {
    private int j = 0;
    String path = null;

    public void fileRead(File file){
StringBuilder attachPhoneNumber = new StringBuilder();
        try{

        FileReader read = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(read);



        while((path = bufferedReader.readLine()) != null){
            String a[] = new String[3];
            a[j] = path;
            j++;
          System.out.println(path);

            System.out.println(a[j]);
        }
        bufferedReader.close();
        }catch(IOException exception){
        exception.printStackTrace();
        }

    }
Run Code Online (Sandbox Code Playgroud)

我需要它来读取每一行字符串并将每一行存储在一个数组中.但都不起作用.我该怎么办呢?

Sea*_*oyd 5

帮自己一个忙,并使用一个为您提供此功能的库,例如

番石榴:

// one String per File
String data = Files.toString(file, Charsets.UTF_8);
// or one String per Line
List<String> data = Files.readLines(file, Charsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)

Commons/IO:

// one String per File
String data = FileUtils.readFileToString(file, "UTF-8");
// or one String per Line
List<String> data = FileUtils.readLines(file, "UTF-8");
Run Code Online (Sandbox Code Playgroud)