Java: How to read a text file

后端 未结 9 2247
青春惊慌失措
青春惊慌失措 2020-11-22 06:58

I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of t

相关标签:
9条回答
  • 2020-11-22 07:23

    Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Guava, formerly known as Google Collections).

    String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
    List<Integer> list = Lists.newArrayList();
    for (String s : text.split("\\s")) {
        list.add(Integer.valueOf(s));
    }
    

    Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!

    Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)

    0 讨论(0)
  • 2020-11-22 07:24

    Look at this example, and try to do your own:

    import java.io.*;
    
    public class ReadFile {
    
        public static void main(String[] args){
            String string = "";
            String file = "textFile.txt";
    
            // Reading
            try{
                InputStream ips = new FileInputStream(file);
                InputStreamReader ipsr = new InputStreamReader(ips);
                BufferedReader br = new BufferedReader(ipsr);
                String line;
                while ((line = br.readLine()) != null){
                    System.out.println(line);
                    string += line + "\n";
                }
                br.close();
            }
            catch (Exception e){
                System.out.println(e.toString());
            }
    
            // Writing
            try {
                FileWriter fw = new FileWriter (file);
                BufferedWriter bw = new BufferedWriter (fw);
                PrintWriter fileOut = new PrintWriter (bw);
                    fileOut.println (string+"\n test of read and write !!");
                fileOut.close();
                System.out.println("the file " + file + " is created!");
            }
            catch (Exception e){
                System.out.println(e.toString());
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:30

    read the file and then do whatever you want java8 Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());

    0 讨论(0)
提交回复
热议问题