Problems sending a message to a player - java

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+++++++++");
}

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.

Handling newline and empty strings with BufferedReader in Java

I am learning Java. I believe I have an issue understanding how BufferedReader processes "\n" or "" strings (newline and empty strings).
If I run the following it will fail if I put either of those strings into the String array.
String [] strings = {"55", "23", ""};
int total = 0;
for (String str : strings)
{
if (str != null) {
total += Integer.valueOf(str);
}
}
System.out.println(total);
This is fine, and makes sense to me. What does not make sense to me is when I run this code in reading in a file.
BufferedReader reader = null;
int total = 0;
try {
reader = new BufferedReader(new FileReader("E:\\Testing\\Numbers.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
total += Integer.valueOf(line);
System.out.println("Total: " + total);
} catch(Exception e){
System.out.println(e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
using a text file that has the following:
5
2
3
It runs without errors. If I add a single blank line in the same file (), it fails with the message For input string: ""
I added an isNumeric function to solve the issue, but I don't understand why the BufferedReader will work when I run the code without any empty lines, even though it does not like the "\n" or "" strings. I looked up valueOf() in the javadocs and I did not see anything that helped me.
Here is my final code that uses the isNumeric function and shows how it sees both the "\n" and "" strings as non-numeric.
BufferedReader reader = null;
int total = 0;
try {
reader = new BufferedReader(new FileReader("E:\\Testing\\Numbers.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
if (isNumeric(line))
{
System.out.println(line);
total += Integer.valueOf(line);
}
System.out.println("Skipping a non numeric value");
}
System.out.println("Total: " + total);
} catch(Exception e){
System.out.println(e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public static boolean isNumeric(String str)
{
try
{
int d = Integer.parseInt(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
6
Skipping a non numeric value
1
Skipping a non numeric value
Skipping a non numeric value
2
Skipping a non numeric value
62
Skipping a non numeric value
23
Skipping a non numeric value
Total: 94
Finally I did see this article on the site, and it is close, but I still could not figure it out.
When using a BufferedReader, the readLine() method will consume any "new line like" characters automatically.
So, in essence, your initial file was
5\n
...
And the \n is simply removed before giving the string to your code. If the line is just \n; then you get "". An easy way to check for that is line.isEmpty().
Regarding: I don't understand why the BufferedReader will work when I run the code without any empty lines; well I don't understand that question. If your code only reads lines with numbers, it doesn't matter that you have code sitting there that could deal with empty lines; or lines containing "invalid" number text.

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

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

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

Categories

Resources