I want to parse multiple strings into variables from a .txt file in java. What's the easiest way to do it?
What's the best way to do it? Should I use the File class and scanner? I've never done it before and can't seem to find a solid guide for it online so I figured I would ask here.
Edit:
The text file I am parsing is 3 columns, the first three are ID NAME BIRTHDATE then actual data.Edit (code from pastie):
public void readFromFile(File file )
{
try
{
System.out.println("success..");
s = new Scanner(file);
BufferedReader input = new BufferedReader(开发者_如何学编程new FileReader(file));
String jj = null;
while((jj = input.readLine())!=null)
{
String [] words = jj.split("\\t");
String name = "";
String id = "";
String birthdate ="";
for (int i = 3; i<words.length; i+=3)
{
id =words[i];
name = words[i+1];
birthdate=words[i+2];
Person p = new Person(id, name, birthdate);
peopleMap.put(p.id,p);
names.add(p);
System.out.println("New entry added to file: "+name+"\\t"+"ID: "
+id+"\\t"+"Birthdate"+birthdate);
}
}
}
catch(IOException e)
{
}
}
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(); }
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.
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?)
精彩评论