-
reading from a file
hey every one
i need some help with reading from a file
i'm trying to read from a file and put the input in an array
for example this is what's in the file (Adam,ross,sarah,susan) i want to read till " , " and put every name in a column of the array
thanx
-
Here is what you need to do,
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Split {
public static void main(String args[]) {
File file = new File("test.txt");
try {
FileReader fr = new FileReader(file);
BufferedReader reader = new BufferedReader(fr);
String read = "";
while ((read = reader.readLine()) != null) {
String[] tokens = read.split(",");
for (int i = 0; i < tokens.length; i++) {
System.out.println("Array element[" + i + "]: " + tokens[i]);
}
}
reader.close();
} catch (IOException io) {
io.printStackTrace();
}
}
}
Here, make sure that the "test.txt" file is in the root folder and contains the same pattern mentioned by you.
The result is,
Code:
Array element[0]: Adam
Array element[1]: ross
Array element[2]: sarah
Array element[3]: susan
What we have used is the String.split(String regex) method. It returns the array of Strings containing the data separated by the regex pattern provided by you. In our case it is "," which is separating the four name values in the file.
Later, you can iterate over the array and display the contents as you want.
Hope that helps,
Goldest
-
thanx
thanx
that was quick and helpful:) ,however it didn't give me the result that i was looking for ,you see the file that i'm trying to read from is written like this
(List of cars to use: ("MA06 XVU", 8999.0, new
CarSpec("Saloon","Ford","Mondeo", (float)1.6,"Diesel", (int)12,"Blue")); ("MA06
UXW", 12900.0, new CarSpec("Estate","Ford","Mondeo", (float)1.8,"Petrol",
(int)6,"Red")); ) i know it's my bad i'm sorry i didn't give you all the info but i thought i can work it out by my self :o
so can you help me out please :D