I'm trying to convert a CSV file into a 2D array however I'm having problems. The code seems to only print out first name in the CSV file 10 times and then gives me an out of bounds exception. E.g if Player name was Rob, it will just print out Rob over and over again.
If any more clarification needed just ask
try{
int col = 0, row = 0;
System.out.println("Reading " + fileName + " ...");
fr = new FileReader(fileName);
bf = new BufferedReader(fr);
String line = bf.readLine();
while (line != null) {
StringTokenizer st = new StringTokenizer(line,",");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
data[row][col] = st.nextToken();
col++;
}
col = 0;
row++;
}
}catch(IOException e){
System.err.println("Cannot find: "+fileName);
}
I think your code reads just one line. Continue the while loop using the following code snippet -
String line = bf.readLine();
while ((line = br.readLine()) != null) {
//place your code here
}
In the above code BufferedReader - br is now ready to read the next line and it continues until the br.readline() returns a null.
Hope it will help.
Thanks a lot.
Related
So I'm trying to make a file reader to read from x line to y line but when i execute the program it reads all the lines of the file and not the lines that should have started and ended, For example if i'm looking an ID in the file it should print de ID, The name of the holder(the next line of the ID Line), and his/her address(Next line of the name Line), but instead of print just that it prints all the ID'S, Names and Addresses of everyone in the file.
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line2;
int count = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(file));
Scanner input2 = new Scanner(file);
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while((line2 = input.readLine()) != null)
{
if(line2.contains(CL.getID()))
{
while(((line2 = readers.readLine()) != null) && readers.getLineNumber() <= count + 3)
{
count++;
System.out.println(line2);
}
input.close();
input2.close();
output.close();
readers.close();
break;
}
}
}catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
I've modified your code because the problem was at the count++ which will eventually led to reading all the lines from your files, and at the line2 = readers.readLine() which will read from the first line of the file again ( the program works half correct because it reads only 3 lines and only if line2 contains your ID ). Now, to make your program work correctly, you need to either use the BufferedReader or the LineNumberReader.
public static void main(String[] args) {
System.out.println("Escriba el ID Del Cliente");
String line2;
File file = new File(yourpathhere);
int lineCount = 0;
try {
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((line2 = readers.readLine()) != null) {
lineCount++;
if (line2.contains(CL.getId())) {
while (line2 != null && readers.getLineNumber() <= lineCount + 3) {
System.out.println(line2);
line2 = readers.readLine();
}
output.close();
readers.close();
break;
}
}
} catch (IOException ex) {
System.out.println("ERRORR!!!!!!");
}
}
PS : pay attention for the getLineNumber() method because it increments the lines read until the moment you're calling it. It means that if we didn't had the lineCount and the ID we're trying to find was at the 6th line, the getLineNumber() value at the moment when line2.contains(CL.getId()) == true was 6, so the readers.getLineNumber() <= 3 will be FALSE and the program won't work correctly anymore. ( We need to keep track for the lines read until the moment we check for the id )
Assuming you have a file with 100 lines and you want to check and print out line 5 to 10 you could try this:
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line;
int count = 0;
int xLine = 5;
int yLine = 10;
try (BufferedReader input = new BufferedReader(new FileReader(file)))
{
while((line = input.readLine()) != null)
{
if(count < xLine)
{
// skip all lines lower then start
continue;
}
else if(count >= xLine && count <= yLine && line.contains(CL.getID()))
{
// print line if line is between lines to read
// and if line contains ID
System.out.println(line);
}
else
{
// break if count is bigger then yLine
break;
}
count++;
}
}
catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
You read all lines till the BufferedReader reaches null. You check if the line contains your ID. Then you check if the count is between the linenumbers you want to check / print. Then you increment the count for the lines processed.
I simplified the try-catch-Block with a try-with-ressources Statement. As for now I don't see what your plans with output and scanner were, so I removed them.
Sorry for the noob question, but I feel like my code is correct but I can't see why the read won't go to the next line:
This is my code so far:
BufferedReader buffer = null;
try {
FileReader file = new FileReader(filename);
buffer = new BufferedReader(file);
String line = buffer.readLine();
String[] separations = line.split(", ");
System.out.println(separations[0]);
while(line!= null) {
this.times.add(separations[0]);
Double number = Double.parseDouble(separations[1]);
allNumbers.add(number);
line = buffer.readLine();
}
The issue was not that the buffer was only reading one line but I was tokenizing the line outside of the loop, so the same information got stored for x number of lines:
Solution:
while (line != null) {
String[] separations = line.split(", "); // this should be inside the loop
if (separations.length > 1) {
this.times.add(separations[0]);
Double number = Double.parseDouble(separations[1]);
allNumbers.add(number);
}
line = buffer.readLine();
}
I have files containing text in pattern like this
Type:status
Origin:some text
Text:some text
URL:some url
Time:time
around 500 lines with same pattern. I want to extract only the text part from it. I tried reading the file with BufferedReader and used indexOf("Text") and indexOf("URL") and subString(i,j) but its giving exception at run time. How can I do this. My code:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
str= str + s;
i = str.indexOf("Text:");
j= str.indexOf("URL:");
String a= str.substring(i, j);
bw.write(a);
}
br.close();
bw.close();
The "Text:" is found first in the 3rd line and "URL:" in the 4th, but if your program doesn't find both strings, it throws an exception.
Even if it worked you would find the same text over and over again.
Try something like this:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
String s;
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
if (s.startsWith("Text:"))
bw.write(s);
}
br.close();
bw.close();
You could use
String[] pieces = str.split(":");
That will give you an array of strings split by what ever you put in the parenthesis. Then if you know the pattern you can get each piece out by iterating through it in a loop. For example: if you know that Type is at [0] and six things in each sequence you can say that the next Type will be at [6] and so on.
You should check for indexes. Of i and j. If one line is wrong, it will skip it and print the line that is wrong to the console. You should probably handle it in a different way but keep in mind that substring shouldn't love indexes of -1.
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String tokenText = "Text:";
String tokenURL = "URL:";
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
String a;
str = str + s;
i = str.indexOf(tokenText);
j = str.indexOf(tokenURL);
if (i < 0 && j >= 0){
// pad with the token string
a = s.substring(j + tokenURL.length);
} else if(i >= 0) {
// pad with the token string
a = s.substring(i + tokenText.length);
} else {
System.out.printl("Unparsed line:");
System.out.printl(s);
}
bw.write(a);
}
br.close();
bw.close();
That said, as jonhchen902 said in the comments, you could also check for the strings after the while loop. It really depends on your input file and if you're expecting to find the "string" multiple times or once.
According to your example, Text: and Url: are on consecutive lines.
Your problem is you're reading the file line by line (br.readLine()), so calling indexOf() will most of the time return -1 in i or j (and you will never find both strings, since they aren't on the same line).
As the javadoc of substring() states, calling the method with a negative start index will throw an IndexOutOfBoundsException. So your approach isn't right.
You should instead parse the file line by line as you're doing, and simply test for a positive index to the call to indexOf("Text:"), and then substring the current line starting at the returned index + 5.
Not tested:
while ((line = br.readLine()) != null) {
i = line.indexOf("Text:");
if (i > 0) {
String text = line.substring(i);
bw.write(text + "\n");
}
}
I wrote a small Java program that reads the data from CSV file and I have to save these values in 2 dimensional array. Now I need to write these values (not all information will be stored because the array contains many redundant data) from this array to a new CSV file. Can anyone help me with a code sample, I searched a lot but could not find an answer. My code is:
int row = 0;
int col = 0;
String[][] numbers=new String[24][24];
File file = new File("D:\\thesis\\sorted_file.csv");
if(file.exists())
{
System.out.println("file exist");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
String delims=",";
//read each line of text file
while((line = bufRdr.readLine()) != null )
{
StringTokenizer st = new StringTokenizer(line,delims);
col=0;
while (st.hasMoreTokens())
{
//get next token and store it in the array
numbers[row][col] = st.nextToken();
System.out.print("number["+row+"]["+col+"]:"+numbers[row][col]);
col++;
}
row++;
}
You can use something like this...
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
for (String element : numbers) {
sb.append(element);
sb.append(",");
}
br.write(sb.toString);
br.close();
I have a method that takes data from a .csv file and puts it into an array backwards
(first row goes in last array slot) however I would like the first row in the .csv file to not be in the array. How would I accomplish this? Here is my code thus far:
public static String[][] parse(String symbol) throws Exception{
String destination = "C:/"+symbol+"_table.csv";
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(destination)));
lnr.skip(Long.MAX_VALUE);
String[][] stock_array = new String[lnr.getLineNumber()][3];
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
String strLine = "";
StringTokenizer st = null;
int line = lnr.getLineNumber()-1;
while((strLine = br.readLine()) != null){
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
stock_array[line][0] = st.nextToken();
st.nextToken();
stock_array[line][1] = st.nextToken();
stock_array[line][2] = st.nextToken();
st.nextToken();
st.nextToken();
st.nextToken();
}
line--;
}
}
catch(Exception e){
System.out.println("Error while reading csv file: " + e);
}
return stock_array;
}
You can skip the first line by just reading it in and doing nothing. Do this just before your while loop:
br.readLine();
To make sure that your array is the right size and lines get stored in the right places, you should also make these changes:
String[][] stock_array = new String[lnr.getLineNumber()-1][3];
...
int line = lnr.getLineNumber()-2;
Your code is not efficient, as far as my knowledge goes. Also, you are using linenumberreader.skip(long.max_value), which is not a correct/confirmed way to find the line count of the file. StringTokenizer is kind of deprecated way of splitting tokens. I would code it, in the following way:
public static List<String[]> parse(String symbol) throws Exception {
String destination = "C:/"+symbol+"_table.csv";
List<String[]> lines = new ArrayList<String[]>();
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
int index = 0;
while((line = br.readLine()) != null){
if(index == 0) {
index++;
continue; //skip first line
}
lines.add(line.split(","));
}
if(lines != null && !lines.isEmpty()) {
Collections.reverse(lines);
}
} catch(IOException ioe){
//IOException Handling
} catch(Exception e){
//Exception Handling
}
return lines;
}