Inputstream reader skips over some text - java

Hi guys so this is an exert from the code I have
public ItemList() throws Exception {
//itemList = new List<Item>() ;
List<Item> itemList = new ArrayList<Item>() ;
URL itemPhrases = new URL("http://dl.dropbox.com/u/18678304/2011/BSc2/phrases.txt"); // Initilize URL
BufferedReader in = new BufferedReader(new InputStreamReader(
itemPhrases.openStream())); // opens Stream from html
while ((inputLine = in.readLine()) != null) {
inputLine = in.readLine();
System.out.println(inputLine);
Item x = new Item(inputLine);
itemList.add(x);
} // validates and reads in list of phrases
for(Item item: itemList){
System.out.println(item.getItem());
}
in.close();// ends input stream
}
My problem is that I am trying to read in a list of phrases from the URL http://dl.dropbox.com/u/18678304/2011/BSc2/phrases.txt but when it prints out what I have collected it just prints:
aaa
bbb
ddd
I have tried researching the library and using the debugger but neither have helped.

You should remove inputLine = in.readLine(); from inside the while loop, it calls readLine() function a second time, thus skipping every second line.
Your loop should look like this:
while ((inputLine = in.readLine()) != null) {
//this line must not be here inputLine = in.readLine();
System.out.println(inputLine);
Item x = new Item(inputLine);
itemList.add(x);
}

You are calling in.readLine() twice in a row. Remove the second call.

Related

BufferedReader does not work well

Loading following URL with BufferedReader, but content is not delivered. Even though a plain browser can show content. So str will remain nil. Any idea why?
URL url = new URL("http://www.omdbapi.com/?t=zorr&y=&plot=short&r=json");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {}
Log.d("alma", str);
You are ignoring all of the lines that you are reading. You then exit the loop when str becomes null. So, your Log.d() call will always show null.
If you want to use the lines that you are reading, use str inside` your currently empty block:
while ((str = in.readLine()) != null) {
// do something with str
}
You might also wish to consider using a third-party library that offers a simpler API. OkHttp3, for example, makes getting a string response from a URL fairly easy.
try this:
URL url = new URL("http://www.omdbapi.com/?t=zorr&y=&plot=short&r=json");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
Log.d("alma", str); // this should be here
}

How to handle ArrayIndexedBoundexception in Java

I have been trying to get a specific columns from a csv file say having 30 columns but i need only 3 columns entirely when i execute the following code only i get only one entire column data..how to get 3 column data at a time.when i run it prints only one column...when i try to print multiple column it shows error message like
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ReadCVS.main(ReadCVS.java:19)
public static void main(String[] args) throws Exception {
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("txt.csv"));
String line = br.readLine();
while((line = br.readLine()) !=null){
String[] b = line.split(splitBy);
PrintWriter out = new PrintWriter(new FileWriter("new.csv",true));
out.println(b[0]);
out.close();
}
br.close();
}
The problem is probably is:
You have only one line in your, txt.csv file.
When you called br.readLine(); for the first time, that line is read from the file and stored in String line variable. But you ignored that line, and you've read again, in your while condition:
while((line = br.readLine()) !=null)
So maybe you have an empty line or empty string after that first line. Then the while condition is true, but an empty String is stored in line variable. So the b[] has no element and b[0] is out of the bound.
One solution is to change this line:
String line = br.readLine();
to
String line = null;
[EDIT]
So if you try to read a file like the one in mkyong's site (as you linked in your comment) and split the lines by "," and write them in a new file for example, you can use a code like the code below:
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
BufferedReader br = new BufferedReader(new FileReader("c:\\txt.csv"));
String splitBy = ",";
String line = null;
while((line = br.readLine()) !=null){
StringBuffer newLine = new StringBuffer();
String[] b = line.split(splitBy);
for (int i = 0; i<b.length; i++)
{
if(b[i] == null || b[i].trim().isEmpty())
continue;
newLine.append(b[i].trim() + ";");
}
out.write(newLine.toString());
out.newLine();
}
out.close();
br.close();
}
Also you should know that the following line opens the output file in appendable way(the second boolean parameter in the constructor):
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
Also I assumed the contents of the source file is the same as in mkyong's site, somethimg like this:
"1.0.0.0",, , ,"1.0.0.255","16777216", , "16777471","AU" ,, "Australia"
"1.0.1.0" , ,, "1.0.3.255" ,, ,"16777472","16778239" , , "CN" , ,"China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Good Luck.

Readline() reads only first line

I need to read a text file and split using a common text in the lines, and print a part of the split text. This works fine but only does this for the first line in the text.
However, if I print lines without the split part, it prints correctly. Please what am I doing wrong?
File sample: (I want to split by "words")
Line 1 This text is of length: 7 words. I need to learn how to program.
Line 2 Now we have text of length: 3 words. No matter what the words are, I must program
FileInputStream fis = new FileInputStream(fin);
//Construct BufferedReader from InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
ArrayList<String> txt1 = new ArrayList<>();
while ((line = br.readLine()) != null) {
String[] pair = line.split("words");
txt1.add(pair[1]);
System.out.println(txt1);
//System.out.println(line);
}
br.close();
Given the following unit test simulating the input of a file via a StringInputStream:
#Test
public void test() throws IOException
{
String fileContent = "This text is of length: 7 words.\r\nI need to learn how to program and one day.";
StringInputStream stream = new StringInputStream(fileContent);
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = null;
ArrayList<String> txt1 = new ArrayList<>();
while ((line = br.readLine()) != null) {
String[] pair = line.split("words");
txt1.add(pair[1]);
System.out.println(txt1);
//System.out.println(line);
}
}
The first line will be split into
"This text is of length: 7 " and
"."
Since you put item [1] into the array list, it'll just contain a single dot.
The second line will be split into
"I need to learn how to program and one day."
only. There is no second item, so accessing [1] results in a ArrayIndexOutOfBoundsException.

Java Outprinting Large File Line By Line

Every time I do something like
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
It won't outprint line by line. Instead it will lag for 2-3 seconds then show it all at once. I've tried putting sleep methods etc. How can I make it so it takes its time and goes through each one rather than just lagging and spitting it all out at once?
Try flushing the output.
System.out.flush();
After each System.out.println
This is probably because your file doesn't have carriage return characters at the end of each line. So, it's considering the entire file as one line.
Try sending the lines to an array list. See if the arraylist contains each line. Then try iterating the array list to the website chunk by chunk.
BufferedReader br = new BufferedReader(new FileReader(f));
ArrayList<String> list = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
for(String one_line: list){
//send lines to website:
//sendLine(one_line);
}

Java - Reading From FIle

I am trying to read some lines from a file in Java. I have 4 lines in the file, but the problem is that it reads only 2 of the lines. Here's the code:
BufferedReader flux_in = new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
String line;
while (flux_in.readLine() != null)
{
line = flux_in.readLine();
System.out.println(line);
}
It is because you are calling readLine twice as often as you should.
Your first call inside the the while condition just threw the line away.
BufferedReader flux_in = new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
String line;
while ((line = flux_in.readLine()) != null)
{
System.out.println(line);
}
It does read all of them, although not quite in the way you'd like.
BufferedReader flux_in = new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
String line;
while (flux_in.readLine()!=null) //one line is read here
{
line = flux_in.readLine(); //the next one here
System.out.println(line);
}
In your code, the call in the loop test consumes a line, and then the call n the loop body consumes another line. So it would only print every other line.
String s = null;
while ((s = flux_in.readLine()) != null)
{
System.out.println(s);
}
BufferedReader is stateful and remembers what has been read from the file already. Every call of readLine() moves the cursor to the next line. You are calling readLine() twice per line: in the while loop and in the line assignment. Try this instead:
String line = flux_in.readLine();
while (line != null) {
System.out.println(line);
line = flux_in.readLine();
}
You're reading the line twice (in the while condition and in the while loop, so it's displaying one and then skipping the next. Change your code to this:
try {
BufferedReader flux_in = new BufferedReader(new FileReader("abc.txt"));
String line;
while ((line = flux_in.readLine()) != null)
System.out.println(line);
} catch(Exception e) { System.out.println("Error"); }

Categories

Resources