I have this simple bit of code causing me a headache
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("Quiz.csv")));
List<String> lines = null;
String line = null;
try {
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
catch (Exception e)
{
Log.e(getLocalClassName(), e.toString());
}
I get a nullPointerException from logcat when I hit the while loop
Your lines is null. Initialise it:
List<String> lines = new ArrayList<String>();
You have to initialize lines like so:
List<String> lines = new ArrayList<String>();
Related
I have a text file which looks like this:
thiasisatest("test1",
"test2",
"test3",
"test4",
"test5");
The output I am trying to achieve is this:
thiasisatest("test1", "test2", "test3", "test4", "test5");
My code looks like this:
import java.io.*;
public class IoTest {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Applications/textfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.trim().replace("\n", ""));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I am reading the line and replacing all lines in the while loop, but the output doesn't change and the lines are still there when I am trying to print out the string.
What am I doing wrong?
Thank you for your help
You actually do not need to replace the line; Because you are technically recalling line by line.
All you need to do is create a StringBuilder to which you append every line from your buffered reader.
Your code should look like this
String sCurrentLine;
StringBuilder builder = new StringBuilder();
while ((sCurrentLine = br.readLine()) != null){
builder.append(sCurrentLine);
}
You can now output the content of the "builder" to another file.
System.out.println
terminates the line, that it why you are getting multiple lines.
I am using the following code to get data from a file
try {
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput(TEXTFILE));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String string;
StringBuilder stringbuilder = new StringBuilder();
while ((string=bufferedReader.readLine())!=null){
stringbuilder.append(string);
}
EditText.setText(stringbuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
It works but
when I put the string=bufferedReader.readLine() before While, I get an exception : java.lang.OutOfMemoryError
You're reading a line from the BufferedReader, and storing the result in string. After that, you check if string != null, and if not, you append string to stringbuilder. You're repeating this until string == null.
The confusion here might be the comparison of an assignment statement:
while ((string = bufferedReader.readLine()) != null) { ... }
This is a short notation of the following:
string = bufferedReader.readLine();
while (string != null) {
...
string = bufferedReader.readLine();
}
Update :: I have changed my code a bit but still bug with lines.get(0) which makes my app crashed again.
final List<String> lines = new ArrayList<String>();
String line;
int i = 0;
BufferedReader buffreader = null;
try {
buffreader = new BufferedReader(
new InputStreamReader(getAssets().open("test.txt")));
while((line = buffreader.readLine()) != null)
{
lines.add(line);
i++;
}
} catch (IOException e) {
}
This
final String lines[]= {};
creates an array of length 0, so you can't access any elements.
Using a List<String> would be a better idea, since you don'T know how many lines you'll read.
List<String> lines = new ArrayList<String>();
// in the loop:
lines.add( line );
use ArrayList<String> array = new ArrayList<String>();
this will allocate memory for you as needed.
I got stuck with an issue, that I can't seem to solve. When splitting I should be able to get id, name, check by setting row[0], row[1], row[2]. Strangely only row[0] (id) seem to work. Name, check gives me an error. Could someone help me further?
Example of data:
id,name,check
1,john,0
1,patrick,0
1,naruto,0
Code:
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(Pattern.quote(","));
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
Error message:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
Solved
It seems I had an incorrect value (question marks) at end of file. When removing this line. My code worked (without Patter.quote). Thank you all for fast reply's. First answer helped me on reminding me of using Log value where I could see the 'incorrect value'. My bad.
Probably in the time:
String[] row = line.split(",");
was called, there was no comma (,) in the line of the file/stream you're trying to read.
Try this code,
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(",");
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
I think you don't need to use Pattern.quote(",") here.
In my experience with txt files this is the best way of dealing with it:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class Cyto {
public static void main(String[] args) throws IOException {
ArrayList<String> names = new ArrayList<String>();
try {
FileInputStream dis = new FileInputStream("list.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while (br.ready()) {
line = br.readLine();
String[] row = line.split(Pattern.quote(","));
System.out.println(row[1]);
names.add(row[1]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use
br.ready()
instead of reading directly from stream.
public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.