How to open a txt file and read numbers in Java

后端 未结 6 1055
佛祖请我去吃肉
佛祖请我去吃肉 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 19:07

       try{
    
        BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println (strLine);
        }
        //Close the input stream
        in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }finally{
         in.close();
        }
    

    This will read line by line,

    If your no. are saperated by newline char. then in place of

     System.out.println (strLine);
    

    You can have

    try{
    int i = Integer.parseInt(strLine);
    }catch(NumberFormatException npe){
    //do something
    }  
    

    If it is separated by spaces then

    try{
        String noInStringArr[] = strLine.split(" ");
    //then you can parse it to Int as above
        }catch(NumberFormatException npe){
        //do something
        }  
    

提交回复
热议问题