Store text file content line by line into array

后端 未结 11 1324
梦毁少年i
梦毁少年i 2020-12-05 12:09

all,I\'m now facing the problem of no idea on storing the content in text file into the array. The situation is like, text file content:

abc1
xyz2
rxy3


        
相关标签:
11条回答
  • 2020-12-05 12:29

    When you do str = in.readLine()) != null you read one line into str variable and if it's not null execute the while block. You do not need to read the line one more time in arr[i] = in.readLine();. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).

    BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
    String str;
    
    List<String> output = new LinkedList<String>();
    
    while((str = in.readLine()) != null){
        output.add(str);
    }
    
    String[] arr = output.toArray(new String[output.size()]);
    
    0 讨论(0)
  • 2020-12-05 12:31

    You can use this full code for your problem. For more details you can check it on appucoder.com

    class FileDemoTwo{
        public static void main(String args[])throws Exception{
            FileDemoTwo ob = new FileDemoTwo();
            BufferedReader in = new BufferedReader(new FileReader("read.txt"));
            String str;
            List<String> list = new ArrayList<String>();
            while((str =in.readLine()) != null ){
                list.add(str);
            }
            String[] stringArr = list.toArray(new String[0]);
            System.out.println(" "+Arrays.toString(stringArr)); 
        }
    
    }
    
    0 讨论(0)
  • 2020-12-05 12:34

    Try this:

    String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
    int i=0;
    while((str = in.readLine()) != null)          
        arr[i++] = str;
    
    System.out.println(Arrays.toString(arr));
    
    0 讨论(0)
  • 2020-12-05 12:41

    Suggest use Apache IOUtils.readLines for this. See link below.

    http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

    0 讨论(0)
  • 2020-12-05 12:42

    You can use this code. This works very fast!

    public String[] loadFileToArray(String fileName) throws IOException {
        String s = new String(Files.readAllBytes(Paths.get(fileName)));
        return Arrays.stream(s.split("\n")).toArray(String[]::new);
    }
    
    0 讨论(0)
提交回复
热议问题