Java: How to read a text file

后端 未结 9 2159
青春惊慌失措
青春惊慌失措 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: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());
            }
        }
    }
    

提交回复
热议问题