I am trying to loop through a text file, and according to my logic it is supposed to loop though while, line is not null, and then in another while loop inside of that loop, its supposed to loop through the line while a variable does not equal one of my command line arguments and then its supposed to take the first token of the line and add it to that variable. But every time I run the code I get no such element exception, i don't understand why?
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
String id = new String();
StringTokenizer st = new StringTokenizer(line, ",");
while(line != null){
while(!id.equals(args[0])){
line = br.readLine();
id = st.nextToken();
}
}
} catch (FileNotFoundException e) {
System.out.println("file not found");
} catch (IOException e) {
System.out.println("not a string");
}
The file looks something like this:
line1: 118, s, m, p
line2: 111, s, m, c
nextToken()
NoSuchElementException--This is thrown if there are no more tokens in
this tokenizer's string
At this code
while(!id.equals(args[0])){
id = st.nextToken();
}
Your loop will continue until your while condition(while(!id.equals(args[0]))) fails. So check your args[0] with id by printing them on console before your while condition.
Modify your code a little bit
String line ="";
String id = new String();
while((line = br.readLine())!= null){
StringTokenizer st = new StringTokenizer(line, ",");
while(!id.equals(args[0])){
id = st.nextToken();
}
}
Your file contains 118, s, m, p .. a space after , so I guess your tockenizer string should be ", "
Related
I'm currently working on an assignment and I cannot find any clue to remove the headline from the text file and write the rest into an ArrayList. Can someone help me?
ID,Nama,GajiPokok,JmlAbsensi,JmlIzin
2,Peter,5000000,17,3
1,John,4500000,19,1
3,Linda,10000000,13,7
4,Lucy,7000000,20,0
Here is my code:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
try {
String line = in.readLine();
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
in.close();
} catch (IOException e){e.printStackTrace();}
If you want to ignore first line while reading the CSV file then you can simple skip processing of 1st line by calling in.readLine(); twice at the start as shown in below example:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
String line = in.readLine();
line = in.readLine(); //skip fist line and read second line
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
Using skip() method of JAVA 8 Streams:
try(BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"))) {
Stream<String> lines = in.lines();
List<Staff> staff = lines.skip(1).map(line -> {
Staff s = new Staff();
String data[] = line.split(",");
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setJmlhAbsensi(Integer.parseInt(data[3]));
s.setJmlhIzin(Integer.parseInt(data[4]));
return s;
}).collect(Collectors.toList());
System.out.println(staff);
}
You can declare the following line twice or initialize integer variable and skip the loop if its zero.
String line = in.readLine();
This solution works.
private void readTextFile(String fileName) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader(fileName));
Stream<String> stream = in.lines();
List<String> answer = stream.collect(Collectors.toList());
// For Pre-Java8
/*for (int i = 1; i < answer.size(); i++) {
System.out.println(answer.get(i));
}*/
// Split afterwards.
Stream<String> ans = answer.stream().filter(p -> !p.equals(answer.get(0)));
ans.forEach(x -> System.out.println(x));
}
the following code will only read the first line of a text file and it will stop there. I've been experimenting with loops but i cannot get it to successfully update the line until there are no more lines in the file. can anyone help? thanks
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("test1.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
Basically, you want to keep reading until you run out of lines, at which time BufferedReader will return null
char[] parse = {' '};
String delims = new String(parse);
String line = null;
while ((line = in.readLine()) != null) {
String[] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
}
You should be managing your resources better, if you open it, you should make all reasonable attempts to close. Currently, if your code fails for some reason, the in.close line will never be called. Also, you shouldn't ignore exceptions
Luckily, in Java 8, this is easy to manage...
try (BufferedReader in = new BufferedReader(new FileReader("test1.txt"))) {
//...
} catch (IOException e) {
e.printStackTrace();
}
Take a closer look at Basic I/O, The try-with-resources Statement and BufferedReader JavaDocs, especially BufferedReader#readLine
You may also want to take a look at LineNumberReader ;)
while((line = in.readLine()) != null){
//process line
}
This nested statement reads a line from the BufferedReader and stores it in line. At the end of the file, readLine() will return null and stop the loop.
So I am trying to extract a piece of code from a txtfile ,the start of the piece being indicated by "# EMPIRES" and the end being indicated by another string starting with a '#'. My program however never finds the start of the piece and keeps on going until it reaches the end of the file.
To try and find out what the problem was I tried first to print every line that it finds.
And here I encountered another problem. My code already stops finding new lines,long before
"# EMPIRES" is even reached.
public String getEmpirestxt(String fileName) {
Scanner sc;
try {
sc = new Scanner(new File(fileName));
String currentLine = sc.nextLine();
StringBuilder empiresText = new StringBuilder(currentLine);
while (!currentLine.startsWith("# EMPIRES")) {
currentLine = sc.nextLine();
System.out.println(currentLine);
}
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
return empiresText.toString();
} catch (FileNotFoundException ex) {
System.out.println("Landed_Titles.txt not found.");
}
return null;
}
The textfile itself :
https://www.wetransfer.com/downloads/a1093792d5ac54b6ccce04afecb9357f20140402095042/505fca
Here is my solution to your problem. I used newBufferedReader instead of the Scanner to read the file. This example works with Java 7.
public String getEmpirestxt2(String fileName) {
Charset charset = Charset.forName("ISO-8859-1");
Path filePath = Paths.get(fileName);
try (BufferedReader reader = Files.newBufferedReader(filePath, charset)) {
String line = null;
// find the start of the piece
while ((line = reader.readLine()) != null && !line.equals(START)) {
}
System.out.println("START: " + line);
// getting the piece
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null && !line.startsWith(END)) {
sb.append(line);
}
System.out.println("END: " + line);
return sb.toString();
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
return null;
}
The constants in the method are:
private static final String START = "# EMPIRES";
private static final String END = "#";
I tested it with your file and it works fine. It also prints the starting and end points of the required piece:
START: # EMPIRES
END: # color={ 144 80 60 }
String currentLine = sc.nextLine();
you are starting reading from the next Line.
The condition:
while (sc.hasNextLine() && currentLine.charAt(0)!='#')
may terminate even if the file has more lines to read, because of the second predicate. If currentLine.charAt(0)!='#' is fales, the while loop ends. This does not mean there are no more lines to read.
In your second while loop you never set currentLine
This part:
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
should be:
do{
currentLine=sc.nextLine();
empiresText.append("\n").append(sc.nextLine());
}while(sc.hasNextLine() && currentLine.charAt(0)!='#');
Otherwise the line right after # EMPIRES won't be read and the code while loop will never stop because the currentLine is not getting updated.
Append currentLine instead of sc.nextLine() in the second while loop :
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
Otherwise you can use a single loop like below :
while (sc.hasNextLine()){
if(sc.nextLine().startsWith("# EMPIRES")){
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
}
}
I am taking a command line input string like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
I want to split this string which is:
String line = "int t; //variable t
t->a = 0; //t->a does something
return 0;"
like this:
String[] arr = line.split("\n");
arr[0] = "int t; //variable t";
arr[1] = "t->a=0; //t->a does something";
arr[2] = "return 0";
but when i run my java program that split function only returns this:
arr[0] = "int t; //variable t";
it didn't returns other two strings that i mentioned above,why this is happening please explain.
The method readLine() will read the input until a new-line character is entered. That new-line character is "\n". Therefore, it won't ever read the String separated by "\n".
One solution:
You can read the lines with a while loop and store them in an ArrayList:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
for (String s : lines) {
System.out.println(s);
}
To stop the while you will have to press Ctrl + z (or Ctrl + d in UNIX, if I'm not wrong).
From your comment you seem to take the input like this
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Here the line represents already split string by \n. When you hit enter on the console, the text entered in one line gets captured into line. As per me you are reading line, only once which captures just int t;//variable t, where there is nothing to split.
This should work!Also make sure if your input contains \n
String[] arr = line.split("\r?\n")
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;
}