Taking input from a file until EOF is found in java -


this question has answer here:

i want take input file using scanner class in java. file format follows:

name: sample.txt  type: txt  comment: odyssey of ulysses  dimension: 3  eof 

what want read above lines until eof file , store value contained in line 'dimension' in variable x. new java , can't understand how using scanner class. tried small code fragment below failed :

scanner in = new scanner(new file("sample.txt")); string line = ""; int x; in.nextline(); in.nextline(); in.nextline(); 

what additional things need add desired input?

example read using scanner

import java.io.file; import java.util.scanner;  public class readingfilesclass {      public static void main(string[] args)     {         try         {             scanner in = new scanner(new file("sample.txt"));             int x = -1;             string line = "";             string[] linesplit;              while (in.hasnextline()) // while scanner reads             {                 line = in.nextline(); // read line                 linesplit = line.split("[a-za-z]+:"); // split line elements                 if (linesplit[0].equals("dimension:") // if first element of splitted string equal dimension:                 {                     x = integer.parseint(linesplit[1].trim()); // assign dimension var 'x' parsing second element, removing trailing spaces first                 }             }              // process contents             // if (x == -1) // means not found             // else // process dimension         } catch (filenotfoundexception x) {             // when not found         }       }  } 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -