read lines in txt file [java]

前端 未结 2 2037
鱼传尺愫
鱼传尺愫 2020-12-18 12:22

I\'ll try to be as clear as possible but pardon me if my question is not perfect. I have a txt file with several lines of data. example:

123 ralph bose 20000 200 1 2

相关标签:
2条回答
  • 2020-12-18 13:13

    There are lots of ways to read an entire line at a time; Scanner is probably easiest:

    final Scanner s = new Scanner(yourFile);
    while(s.hasNextLine()) {
        final String line = s.nextLine();
        YourClass.processLine(line);
    }
    
    0 讨论(0)
  • 2020-12-18 13:20
    void readLine(String fileName)
    {
       java.io.BufferedReader br = null;
       try
       {
          br = new java.io.BufferedReader(new java.io.FileReader(fileName));
          String line = null;
          while(true)
          {
              line = br.readLine();
              if(line == null)
                 break;
              // process your line here
          }
       }catch(Exception e){
       }finally{
         if(br != null)
          {
             try{br.close();}catch(Exception e){}
           }
       }
    }
    

    Also if you want to split strings... use

    String classes split method. for splitting depending on space... you can do ... line.split("\\s*")

    Hope it works

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