How to clear BufferedReader if it isn't empty [Java/Android] - java

I don't understand how to clear a BufferedReader. When I push button in Activity, the variable is set to 1 or 2. Depend on number change file in BufferedReader. When I push second time in buffer will be two files. How to tell BR to clear buffer before second will be upload. And vice versa, of course.
public List<String> getQuestionLinesList() {
String line;
List<String> lines = new ArrayList<String>();
Log.d(TAG, " Trying to get resourses");
Resources res = context.getResources();
try {
if (selectedBox == 1) {
bufferedQuestions = new BufferedReader(new InputStreamReader(res.openRawResource(R.raw.questions_list)));
} else if (selectedBox == 2) {
bufferedQuestions = new BufferedReader(new InputStreamReader(res.openRawResource(R.raw.questions_list_art)));
}
Log.d(TAG, "number i = " + Integer.toString(selectedBox));
while ((line = bufferedQuestions.readLine()) != null) {
lines.add(line);
Log.d(LINETAG, line);
}
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}

Maybe you can try using a local variable in your method for BufferedReader not "bufferedQuestions" that you probably declared like a field in the class where that method : "getQuestionLinesList" belongs.

Add a carriage/ \n at the end of your files, then readLine() should be able to clear your BufferedReader.
JavaDocs for BufferedRead which states
public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Related

Trying to read multiple lines of cmd input

I'm trying to write a method that:
Prints out a message (Something like: "Paste your input: ")
Waits that the user presses enter.
Reads all the lines, that got pasted and adds them up in one String.
(An empty line can be used to determine the end of the input.)
The first syso does the printing part and also the first line gets read correctly, but then it never exits the while loop. Why? There has to be an end?
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = buffer.readLine()) != null && !line.isBlank())
res += "\n" + line;
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Ive already seen the following sites, but they all didn't help:
How to read input with multiple lines in Java
https://www.techiedelight.com/read-multi-line-input-console-java/
Make the console wait for a user input to close
Edit:
The same bug applies for:
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Edit 2:
I've tried this code in my actual project and in a new test-project, but with different results. Here is a video of that test.
Why wouldn't use this statement?
while (!(line = buffer.readLine()).isEmpty())
In this case sending empty line will exit the loop.
Although, if you insert large text with empty lines (for example, the beginning of a new paragraph, or a space between them) will terminate the program.

Detect first line of text file separately?

I am designing a program that will load a text file into different media file classes (Media > Audio > mp3, Media > Video > Avi, etc).
Now the first line of my text file is how many files there are in total, as in
3
exmaple.mp3,fawg,gseges
test.gif,wfwa,rgeg
ayylmao.avi,awf,gesg
Now that is what is in my text file, I want to first get the first line separately, then loop through the rest of the files.
Now I understand I can simply count how many files are in by using an int that grows as I loop but I want it clear in the file aswell, and I'm not sure how to go about this.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while(line != null)
{
//Get the first line of the text file seperatly? (Then maybe remove it? idk)
//Split string, create a temp media file and add it to a list for the rest of the lines
}
//String[] split = s.next().split(",");
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
I hope my question is clear, if it TL;DR I want to get the first line of a text file separately, then the rest Id like to loop through.
I wouldn't advice using a for-loop here, since the file might contain additional lines (e.g. comments or blank lines) to make it more human-readable. By examining the content of each line, you can make your processing more robust against this sort of thing.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
String line = reader.readLine(); // <-- Get the first line. You could consider reader as a queue (sort-of), where readLine() dequeues the first element in the reader queue.
int numberOfItems = Integer.valueOf(line); // <-- Create an int of that line.
// Do the rest:
while((line = reader.readLine()) != null) // <-- Each call to reader.readLine() will get the next line in the buffer, so the first time around this will give you the second line, etc. until there are no lines left to read.
{
// You will not get the header here, only the rest.
if(!line.isEmpty() || line.startsWith("#") {
// If the line is not empty and doesn't start with a comment character (I chose # here).
String[] split = line.split(",");
String fileName = split[0];
// etc...
}
}
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
You don't need while loop to read up to end of file. Read first line and convert it to int than loop through.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
int lineNo=Integer.parseInt(reader.readLine());
// Now read upto lineNo
for(int i=0; i < lineNo; i++){
//Do what you need with other lines.
String[] values = reader.readLine().split(",");
}
} catch (Exception e) {
//Your exception handling goes here
}
}

Line when reading a file is empty but the line is not null

I have a problem in java and i dont understand why, since i think i am doing text-book stuff.
An overview in what of want to do is:
I want to create a file that contains in each line two strings: documentPath, documentID (in this format: "documentPath;documentID;")
I want to be able to add lines at the end of the file and load the file to a Java Data Structure, lets say a HashSet.
Each time i want to add a new line, i load all the file in a HashSet, check if the line i want to add is not already there and eventually add it at the end. (small number of data - don't care about efficiency)
The code
Add file:
public void addFile(String documentPath) {
this.loadCollection(); //METHOD IS NOT CONTINUING: ERROR HERE
if (!documentsInfo.contains(documentPath)) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(this.collectionFile, true)));
DocumentInfo documentInfo = new DocumentInfo(documentPath, ++this.IDcounter);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Load file:
public void loadCollection() {
if (loaded) {return;}
BufferedReader br;
try {
br = new BufferedReader(new FileReader(collectionFile));
String line;
while ( (line = br.readLine())!= null ) { //PROBLEM HERE
System.out.println("the line readed from file-" + line + "-");
System.out.println("is the line null: "+ (line==null));
System.out.println("line length: " + line.length());
DocumentInfo documentInfo = new DocumentInfo(line);
documentsInfo.add(documentInfo);
}
br.close();
open = true;
} catch (IOException e) {
e.printStackTrace();
}
}
create the line to add:
public DocumentInfo(String fileLine) {
String delimiter = Repository.DOCUMENT_FILE_SEPARATOR;
StringTokenizer tok = new StringTokenizer(fileLine, delimiter);
System.out.println("Tokenizer starts with string: " + fileLine);
this.documentPath = tok.nextToken(); //EXCEPTION here
this.documentId = Integer.parseInt(tok.nextToken());
}
public String toString() {
String sep = Repository.DOCUMENT_FILE_SEPARATOR;
return this.getDocumentPath()+sep+this.getDocumentId()+sep+"\n";
}
I am getting the exception at the Tokenizer method (java.util.NoSuchElementException) when i try to get the nextToken, but the problem comes from the loadCollection() method. The first time i read the contents of the file nothing is there, the line is empty (lenght: 0) but the line is not null, so the while-condition fails to stop the while iteration.
Here is what i get from the debbuging prints:
the line readed from file--
is the line null: false
line length: 0
Tokenizer starts with string:
Can anyone help me with this?
You get a null only when you have exhausted the stream. But the first line of the stream (your file) is just an empty line - and you load it, the result of the empty line, is an empty string (""). It can be easily solved by skipping lines with string.length() == 0, by adding the following in your while loop:
if (line.length() == 0) continue;
You might want to consider using trim() before checking the length as well, to avoid nasty spaces making the string.length() > 0

wrong Reading with BufferedReader

I have problem with reading data from file.
In each line (except first) first char is lost!
Maybe i have troubles with coding, but i try to set UTF-8, UniCode, ANSI, and result is fast the same...
Code:
try (FileReader fr = new FileReader("123.txt")) {
// create a buffer for file reader
BufferedReader br = new BufferedReader(fr);
do {
input = br.readLine();
System.out.println(input);
} while (br.read() != -1);
} catch (IOException ex) {
System.out.println("IOex : " + ex);
}
Console:
2
FFFFFF
FAF9F5
FDBCA1
FBCCB8
but must be:
2
#FFFFFF
2
#FAF9F5
6
#FDBCA1
9
#FBCCB8
9
it only works, when i put slashes before lines.
2
\#FFFFFF
\2
\#FAF9F5
\6
\#FDBCA1
\9
\#FBCCB8
\9
What can it be?
Thanks!
The problem is with the end of your do loop:
do {
input = br.readLine();
if (input.endsWith("\n")) {
input = input.substring(0, input.indexOf("\n"));
}
System.out.println(input);
} while (br.read() != -1);
You're calling read() which will read the first character of the next line - but you're only using that to check for whether the file has ended. (Notice how you've got the first character of the first line, because there you're calling readLine without previously calling read.)
This would work fine - and be simpler:
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
readLine returns null when you've reached the end of the data. Note that you don't need to check for input containing \n as you're already reading one line at a time, and \n is deemed to be a line separator.

Problems sending a message to a player

I have a problem with my bukkit plugin.
What I try to do is search through a file, and read it line by line (that works), then if the line has some text in it, it has to return that line, but it also has to return all the other lines in the file which also have that specific text in it. And when i have these lines, i have to send these lines in a message to the Player, that is not the problem, but when i send the lines i get now, the "\n" doesn't work, here is the code i use now:
public String searchText(String text, String file, Player p)
{
String data = null;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine()) != null)
{
if(line.indexOf(text) >= 0)
{
data += System.getProperty("line.separator") + line + System.getProperty("line.separator");
}
p.sendMessage("+++++++++++GriefLog+++++++++++");
p.sendMessage(data);
p.sendMessage("++++++++++GriefLogEnd+++++++++");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
The return is meant to be empty, because the info is returned to the player a bit higher:P
The problem now is, how do i add an "\n" to the data variable, because when i use this function in the rest of my code, it gives a lot of lines, but without the "\n", so how do i put that in?
Since your method isn't supposed to return anything, remove your return statement and set the return type to void.
It looks like your code would output the data string once for each line your search term occurs, try:
data = "";
while((line = br.readLine()) != null)
{
if(line.indexOf(text) >= 0)
{
//remove the first System.getProperty("line.separator") if
//you don't want a leading empty line
data += System.getProperty("line.separator") + line +
System.getProperty("line.separator");
}
}
if (data.length() > 0) {
p.sendMessage("+++++++++++GriefLog+++++++++++");
p.sendMessage(data);
p.sendMessage("++++++++++GriefLogEnd+++++++++");
}

Categories

Resources