What's the best way to do it? Should I use the File class and scanner? I've never done it before and cant seem to find a solid guide for it online so I figured I would ask here.
Thanks!
What's the best way to do it? Should I use the File class and scanner? I've never done it before and cant seem to find a solid guide for it online so I figured I would ask here.
Thanks!
If you are free to say what the syntax / structure of the text file is, then consider making it a Java properties file. Then you can load and save the file with minimal programming effort using the java.util.Properties
class.
The easiest way depends on the format of the text file. From your other comment, it sounds like the lines are tab separated values. As a beginner you will probably find it simplest to use Scanner. Specifically, Scanner.nextLine(). Couple that with using String.split("\t") to split the data into an array (assuming the format is tab-separated-values).
Simply depends on the format of the text file.
If its simple name value pair then you can use java.util.Properties. for example a.properties could look like:
name=john city=san jose date=12 july 2010
then you can load this as:
Properties props = new Properties();
props.load(new FileInputStream("a.properties"));
If format is different than what is supported by java.util.Properties.load() then using java.util.Scanner would be helpful to process it line by line:
File file = new File("data.txt"); try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Process each line seperately
processLine(line);
}
} catch (FileNotFoundException e) { e.printStackTrace(); }
This is what I like to do in that situation:
Scanner s = new Scanner(file);
Scanner line;
String name;
String date;
int id;
while(s.hasNext()){
line = new Scanner(s.nextLine());
id = line.nextInt();
name = line.next/*String*/();
date = line.next/*String*/();
/* Do something with id, name and date */
}
Maybe there is some exception handling or something like that
(Anyone want to comment on the efficiency of creating many new Scanners?)