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.
Related
I have to make an EPG app using java, but I am kind of new in programming and it's due tomorrow and it's still not working properly.
I have a question about a small part: I have to read the programs from a text file. Each line contains multiple things, the channel, the title of the program, a subtitle, a category, etcetera.
I have to make sure that I can read the separate parts of each line, but it's not really working, it's only printing the parts from the first line.
I am trying, but I can't find why it's not printing all the parts from all the lines in stead of printing only the parts from the first line. Here's the code:
BufferedReader reader = new BufferedReader(newFileReader(filepath));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
}
String[] parts = line.split("\\|", -1);
for(int i = 0; i < parts.length; i++) {
System.out.println(parts[i]);
}
reader.close();
Does anybody know how to get all the lines in stead of only the first?
Thank you!
readLine() only reads one line, so you need to loop it, as you said.
BUT with reading to the String inside of the while loop you always overwrite that String.
You would need to declare the String above the while loop that you can access it from outside, too.
BTW, it seems that your braces for the if don't match.
Anyway, I'd fill the information into an ArrayList, look below:
List<String> list = new ArrayList<>();
String content;
// readLine() and close() may throw errors, so they require you to catch it…
try {
while ((content = reader.readLine()) != null) {
list.add(content);
}
reader.close();
} catch (IOException e) {
// This just prints the error log to the console if something goes wrong
e.printStackTrace();
}
// Now proceed with your list, e.g. retrieve first item and split
String[] parts = list.get(0).split("\\|", -1);
// You can simplify the for loop like this,
// you call this for each:
for (String s : parts) {
System.out.println(s);
}
Use apache commons lib
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
As ArrayList is Dynamic,try,
private static List<String> readFile(String filepath) {
String line = null;
List<String> list = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filepath));
while((line = reader.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
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
}
}
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
I am not sure what went wrong but the printout only give me completely the information form the txt file only on the second time. The first time it will only print out the first line that is in my txt file. Hope someone can point out my mistake.
Here's my code:
public static void main(String[]args) {
try {
FileReader fileReader = new FileReader("data_file/Contact.txt");
BufferedReader in = new BufferedReader(fileReader);
String currentContact = in.readLine();
StringBuilder sb = new StringBuilder();
while(currentContact != null) {
StringBuilder current = sb.append(currentContact);
current.append(System.getProperty("line.separator"));
JOptionPane.showMessageDialog(null, "Contact : \n" + current);
// System.out.println("Contact:" + currentContact);
currentContact = in.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Move
JOptionPane.showMessageDialog(null, "Contact : \n" + current);
outside your while loop (and change it to use sb rather than current). That will show the dialog only after the whole file has been read. Right now you're showing a dialog for each line in your input file.
Incidentally, you could replace this:
StringBuilder current = sb.append(currentContact);
current.append(System.getProperty("line.separator"));
with this:
sb.append(currentContact);
sb.append(System.getProperty("line.separator"));
or even do it on one line:
sb.append(currentContact).append(System.getProperty("line.separator"));
StringBuffer.append returns the object that it is called on. This allows you to chain calls to append.
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+++++++++");
}