reading a txt file
hello..I have a txt file adina.txt who looks like this
name1 name2
name3 name4
name5 name6
I have to read from this file line by line and create everytime a file with the name from the right side:a file name2,a file name4 and a file name6.In these files you have to put the name that you read from the left side.So name1 will be in name2,name3 in name4 and name5 in name6.
I'm new in programming and it's diificult to understand the reading from a file.If you can help,I'll be very grateful
I will help you by showing you what you need to start reading to learn how to do it yourself:
http://java.sun.com/docs/books/tutorial/essential/io/index.html
U can use BufferedReader for reading a file line by line.
BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
Split each line using split() method.
Now get the tokens .
String line = "";
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(" ");
}
Create a new file from the above token.
Write contents into the file using FileWriter's write method. dont forget to
close the writer after writing.
FileWriter fileWriter = new FileWriter(targetFile);
fileWriter.write(contents);
fileWriter.close();
> hoe can I take the third element from a line with
> StringTokenizer?
The method above is a better way to split the string. If you view the StringTokenizer api it even tells you that.....
"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead. "