Read text file into an array

后端 未结 5 878
遥遥无期
遥遥无期 2020-12-10 03:40

I want read a text file into an array. How can I do that?

data = new String[lines.size]

I don\'t want to hard code 10 in the array.

<         


        
相关标签:
5条回答
  • 2020-12-10 04:25

    you can do something like this:

      BufferedReader reader = new BufferedReader(new FileReader("file.text"));
        int Counter = 1;
        String line;
        while ((line = reader.readLine()) != null) {
            //read the line 
            Scanner scanner = new Scanner(line);
           //now split line using char you want and save it to array
            for (String token : line.split("@")) {
                //add element to array here 
                System.out.println(token);
            }
        }
        reader.close();
    
    0 讨论(0)
  • 2020-12-10 04:30
    File txt = new File("file.txt");
    Scanner scan = new Scanner(txt);
    ArrayList<String> data = new ArrayList<String>() ;
    while(scan.hasNextLine()){
        data.add(scan.nextLine());
    }
    System.out.println(data);
    String[] simpleArray = data.toArray(new String[]{});
    
    0 讨论(0)
  • 2020-12-10 04:31

    If you aren't allowed to do it dtechs way, and use an ArrayList, Read it 2 times: First, to get the number of lines to declare the array, and the second time to fill it.

    0 讨论(0)
  • 2020-12-10 04:37

    Use an ArrayList or an other dynamic datastructure:

    BufferedReader abc = new BufferedReader(new FileReader(myfile));
    List<String> lines = new ArrayList<String>();
    
    while((String line = abc.readLine()) != null) {
        lines.add(line);
        System.out.println(data);
    }
    abc.close();
    
    // If you want to convert to a String[]
    String[] data = lines.toArray(new String[]{});
    
    0 讨论(0)
  • 2020-12-10 04:41

    Use a List instead. In the end, if you want, you can convert it back to an String[].

    BufferedReader abc = new BufferedReader(new FileReader(myfile));
    List<String> data = new ArrayList<String>();
    String s;
    while((s=abc.readLine())!=null) {
        data.add(s);
        System.out.println(s);
    }
    abc.close();
    
    0 讨论(0)
提交回复
热议问题