简体   繁体   中英

Reading text file line by line in NetBeans

I'm using the following code to read from a file

int lineNumber = 0;
  try{
       BufferedReader in = new BufferedReader (new FileReader("electric.txt"));
  String line = null;
    while((line = in.readLine()) != null){
     lineNumber++;
     system.out.println("Line "+ lineNumber + " : "+ line);
     }
   } catch(IOException e){
     e.printStackTrace();
   }

My file have specific values on each line, for exemple first line is int, second string, third boolean etc...

My question is how do I get each data type in a variable?

Basically, in a naive approach, you just do as many reads as you need:

String firstLine = in.readLine();
String secondLine = in.readLine();
...

Then you could do something like:

Whatever dataObject = new Whatever(firstLine, secondLine, ...);

for example (maybe within a loop, as you probably want to read the data for many data objects, not just a single one).

In other words: you read the required attributes in some helper variables, to then push those into the object you want to fill with data. Advantage: this works for very large data, as you only read a few lines at a time. Downside: you have to worry about invalid files, missing lines, and such things (so you need quite a bit of error handling).

Alternatively: simply read the whole file into memory first, for example using List<String> allLines = java.util.Files.readAllLines(somePathToYourFile); Then, you iterate these allLines an further process your content, now without worrying about IOExceptions for example.

If you want to check whether the line is boolean, integer, or String, this is a possible solution. If you need to check that the line is long or short, double or float, etc. You still have to handle those cases.

System.out.println("Line " + lineNumber + " : " + line + ", Datatype: " + typeChecker(line));

public static String typeChecker(String line){
    if (line.equals("true")||line.equals("false"))
    return "boolean";
    else{ if (isInteger(line))
        return "int";
    }
    return "String";
}

public static boolean isInteger(String s) {
    try { 
       Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
       return false; 
    } catch(NullPointerException e) {
       return false;
    }
return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM