簡體   English   中英

如何從文件讀取到數組

[英]How do I read from a File to an array

我正在嘗試從文件讀取到數組。 我嘗試了兩種不同的樣式,但都無法使用。 以下是這兩種樣式。

樣式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();

        }
    }

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

    }

我需要它來讀取字符串的每一行並將每一行存儲在一個數組中。 但是兩者都不起作用。 我該怎么辦?

請幫自己一個忙,並使用可以為您提供此功能的庫,例如

番石榴

// 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);

公用/ 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");

目前還不清楚您到底想做什么(部分注釋了很多代碼,而其他代碼甚至無法編譯),但是我建議您考慮使用Guava

List<String> lines = Files.readLines(file, Charsets.UTF_8);

這樣,您根本不需要弄亂自己處理的文件。

暫無
暫無

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

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