Java 如何从文件读取到数组

Java 如何从文件读取到数组,java,arrays,file-io,Java,Arrays,File Io,我正在尝试从文件读取到数组。我尝试了两种不同的风格,但都不起作用。下面是两种风格 风格1 我需要它来读取字符串的每一行,并将每一行存储在一个数组中。但两者都不起作用。我该怎么做呢?现在还不清楚您到底想做什么(部分原因是大量代码被注释掉,留下了其他甚至无法编译的代码),但我建议您考虑使用: List lines=Files.readLines(文件,Charsets.UTF_8); 这样,您就不需要自己处理文件了。帮自己一个忙,使用一个为您提供此功能的库,例如 : //每个文件一个字符串 字符串

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

风格1
我需要它来读取字符串的每一行,并将每一行存储在一个数组中。但两者都不起作用。我该怎么做呢?

现在还不清楚您到底想做什么(部分原因是大量代码被注释掉,留下了其他甚至无法编译的代码),但我建议您考虑使用:

List lines=Files.readLines(文件,Charsets.UTF_8);

这样,您就不需要自己处理文件了。

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

:

//每个文件一个字符串
字符串数据=Files.toString(文件,Charsets.UTF_8);
//或者每行一个字符串
列表数据=Files.readLines(文件,Charsets.UTF_8);
:

//每个文件一个字符串
字符串数据=FileUtils.readFileToString(文件,“UTF-8”);
//或者每行一个字符串
列表数据=FileUtils.readLines(文件“UTF-8”);

它们如何不工作?(输出中有哪些错误或不正确?)请只发布代码的相关部分,而不是注释掉的内容。
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();

        }
    }
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();
        }

    }
List<String> lines = Files.readLines(file, Charsets.UTF_8);
// 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);
// one String per File
String data = FileUtils.readFileToString(file, "UTF-8");
// or one String per Line
List<String> data = FileUtils.readLines(file, "UTF-8");