How to open a txt file and read numbers in Java

后端 未结 6 1046
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 18:17

How can I open a .txt file and read numbers separated by enters or spaces into an array list?

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 18:54

    import java.io.*;  
    public class DataStreamExample {  
         public static void main(String args[]){    
              try{    
                FileWriter  fin=new FileWriter("testout.txt");    
                BufferedWriter d = new BufferedWriter(fin);
                int a[] = new int[3];
                a[0]=1;
                a[1]=22;
                a[2]=3;
                String s="";
                for(int i=0;i<3;i++)
                {
                    s=Integer.toString(a[i]);
                    d.write(s);
                    d.newLine();
                }
    
                System.out.println("Success");
                d.close();
                fin.close();    
    
    
    
                FileReader in=new FileReader("testout.txt");
                BufferedReader br=new BufferedReader(in);
                String i="";
                int sum=0;
                while ((i=br.readLine())!= null)
                {
                    sum += Integer.parseInt(i);
                }
                System.out.println(sum);
              }catch(Exception e){System.out.println(e);}    
             }    
            }  
    

    OUTPUT:: Success 26

    Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file. input-convert-Write-Process... its that simple.

提交回复
热议问题