Store text file content line by line into array

后端 未结 11 1323
梦毁少年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:16

    You need to do something like this for your case:-

    int i = 0;
    while((str = in.readLine()) != null){
        arr[i] = str;
        i++;
    }
    

    But note that the arr should be declared properly, according to the number of entries in your file.

    Suggestion:- Use a List instead(Look at @Kevin Bowersox post for that)

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

    The simplest solution:

    List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
    String[] a = list.toArray(new String[list.size()]); 
    

    Note that java.nio.file.Files is since 1.7

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

    I would recommend using an ArrayList, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.

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

    JAVA 8 :

    Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-05 12:28

    Just use Apache Commons IO

    List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));
    
    0 讨论(0)
  • 2020-12-05 12:29

    This should work because it uses List as you don't know how many lines will be there in the file and also they may change later.

    BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
    String str=null;
    ArrayList<String> lines = new ArrayList<String>();
    while((str = in.readLine()) != null){
        lines.add(str);
    }
    String[] linesArray = lines.toArray(new String[lines.size()]);
    
    0 讨论(0)
提交回复
热议问题