I have a text document separated by tabs. Each line has the same type of information repeated. When I use hasNextLine() and a counter to count the lines it only counts a portion of the lines. I can still create Arrays of the size of the counter I do get. When I use a for loop to fill the Arrays in the results are unexpected.
Here is a summary of what I did.
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
Scanner input = new Scanner(new File("input.txt"));
int lines = 0;
input.nextLine(); //for the header of the table
while(input.hasNextLine()) {
lines++;
input.nextLine();
}
System.out.println(lines);//here I don't get the total amount
String[] colors = new String[lines];
int[] number = new int[lines];
fillArray(colors, number);
System.out.println(colors[i] + i);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void fillArray(String[] color, int[] numbers) {
try {
Scanner input = new Scanner(new File("input.txt"));
input.nextLine(); //for table header
input.useDelimiter("\\t");
for(int i = 0; i < color.length; i++) {
color[i] = input.next();
input.next(); //info i'm not using
numbers[i] = input.nextInt();
input.nextLine(); //consumes '\n'
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
it compiles but my results look like this:
null\\n yellow0\\n null1\\n null2\\n null3\\n etc.
it also shows the correct color and number; but only for one line.
Any help would be appreciated. I haven't used useDelimiter much but from what I understand it will make '\\t' separate tokens instead of white space and '\\n'
Don't get bothered, use that:
final List<String> lines = Files.readAllLines(Paths.get("input.txt"),
StandardCharsets.UTF_8);
The number of lines read is then as easy as lines.size()
, and you just have to walk the list in order to treat your lines.
You may use OpenCSV http://opencsv.sourceforge.net/#custom-sepators . IT is really easy to implement a CSV Reader program using it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.