I am trying to read a Stream which will read until it ends with some string. I came up with some solution but I do not believe it is very good solution because of lots of string conversion and call to method in loop. Could someone please suggest me better solution.
private static String readUntilEndsWith(BufferedReader reader,
String endString) throws IOException
{
StringBuffer buffer = new StringBuffer();
while (!buffer.toString().endsWith(endString))
buffer.append(reader.readLine());
return buffer.toString();
}
Read the current line only and evaluate it. If the line is ok, append it into your buffer and keep reading. This way you only evaluate the current line in the reader and not the whole content.
StringBuilder buffer = new StringBuilder();
String line = reader.readLine();
while (line != null && !line.endsWith(endString)) {
buffer.append(line);
line = reader.readLine();
}
if (line != null) {
buffer.append(line);
}
return buffer.toString();
If your endString is always a string that is in a line, then you can remake your condition to:
String line="";
do{
line=reader.readLine();
buffer.append(line);
}while (!line.endsWith(endString));
this way you do not have to convert your Buffer each time to a string.
P.S.
i also recommend using StringBuilder instead of StringBuffer
if your endString is however something that might be a sum of few lines, you can add something like:
if(endString.endsWith(line) {
if(buffer.toString().endsWith(endString)
return buffer.toString();
}
Related
Using Scanner, i'm not sure how to read a file with multiple lines and store it all into a String. I use a loop like :
while(file.hasNext())
{
string += file.nextLine();
}
I find that the file.hasNext method eats up all of the data in the file and so file.nextInt() doesn't have any values to find and so it returns and error. What can I do to "reset" the Scanner? I tried creating a new Scanner object but that didn't change anything. I have to run this string through a method and I have run into this problem many times. What should I do?
Maybe you should try StringBuilder.
StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
builder.append(line);
// process the line.
}
}
later
String text = builder.toString();
To read the entire contents of a Scanner source into a String, set the Scanner's delimiter to the end of the file:
String contents = file.useDelimiter("\\Z").next();
I know how to read in lines with Scanner, but how do I use a BufferedReader? I want to be able to read lines into an array. I am able to use the hasNext() function with a Scanner but not a BufferedReader, that is the only thing I don't know how to do. How do I check when the end of the file text has been reached?
BufferedReader reader = new BufferedReader(new FileReader("weblog.txt"));
String[] fileRead = new String[2990];
int count = 0;
while (fileRead[count] != null) {
fileRead[count] = reader.readLine();
count++;
}
readLine() returns null after reaching EOF.
Just
do {
fileRead[count] = reader.readLine();
count++;
} while (fileRead[count-1]) != null);
Of course this piece of code is not the recommended way of reading the file, but shows how it might be done if you want to do it exactly the way you attempted to ( some predefined size array, counter etc. )
The documentation states that readLine() returns null if the end of the stream is reached.
The usual idiom is to update the variable that holds the current line in the while condition and check if it's not null:
String currentLine;
while((currentLine = reader.readLine()) != null) {
//do something with line
}
As an aside, you might not know in advance the number of lines you will read, so I suggest you use a list instead of an array.
If you plan to read all the file's content, you can use Files.readAllLines instead:
//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);
using readLine(), try-with-resources and Vector
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\weblog.txt")))
{
String line;
Vector<String> fileRead = new Vector<String>();
while ((line = bufferedReader.readLine()) != null) {
fileRead.add(line);
}
} catch (IOException exception) {
exception.printStackTrace();
}
Hi I was looking to get some help with skipping null lines, I've searched for answers but im not able to find any. This is the code I'm trying to use:
BufferedReader in = new BufferedReader(new FileReader(newest));
String line = "";
while (true) {
if ((line = in.readLine()) == null) {
I would expect the code to look something like this:
String line;
while ((line=in.readLine())!=null) {
if (!line.isEmpty()) {
// do stuff
}
}
Normally I'd trim each line before checking if it is empty, but you say you want to exclude "a line that is blank and has no spaces", which implies you want to include lines that are just space.
If you do want to skip lines that are all whitespace, you could do this:
String line;
while ((line=in.readLine())!=null) {
if (!line.trim().isEmpty()) {
// do stuff
}
}
The point of the while condition is that the BufferedReader will return null when the input is finished, so that should trigger the end of the loop.
Lines won't be null, they may just be empty. What I would do is check if it is empty:
if ((line = in.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
}
}
While reading from this stream, null will only be encountered at the end of the stream (file in this case). If you're looking for an empty/blank string, that test is within the loop (below).
Note that String.trim() does not trim the object itself, it returns the trimmed String. Equals method should generally be used to test for Object (such as String) equality.
BufferedReader in = new BufferedReader(new FileReader(newest));
String line = "";
//Line below keeps looping while the reader return a valid line of text.
//If the end of stream (file in this case) has been reached, you'll get null.
while ((line=in.readLine())!=null) {
//line below tests for empty line
if(line.trim().equals(""){
}
}
I was looking through a lot of diffrent subjects here on stackoverflow but couldn't find anything helpful so far :/
So this is my problem. I am writing a filecopier. The problem occurs already at reading the file. My test docoument got 3 lines of random text. All those 3 lines should get written in a string array. The problem is that only the 2nd line of the textdocument gets written in the array and I can't figure out why. Already debugged it, but didn't get me any further.
I know there are diffrent solutions for a filecopier with diffrent classes etc. But I would really like to get it running with the classes I used here.
String[] array = new String[5];
String datei = "test.txt";
public String[] readfile() throws FileNotFoundException {
FileReader fr = new FileReader(datei);
BufferedReader bf = new BufferedReader(fr);
try {
int i=0;
//String Zeile = bf.readLine();
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return array;
You're calling readLine() twice for each iteration of the loop, thereby discarding every other line. You need to capture the value returned by every call to readLine(), because each readLine() call advances the reader's position in the file.
Here's the idiomatic solution:
String line;
while((line = bf.readLine()) != null){
array[i] = line;
i++;
}
Here you read 2 lines:
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
You have to change your Code to:
String line = null;
while((line =bf.readLine()) != null){
array[i] = line;
// System.out.println(array[i]); This line is for testing
i++;
}
The problem is here :
while(bf.readLine() != null)
readLine() reads a line and returns the same at the same time it moves to the next line.
So instead of just checking if the returned value was null also store it.
String txt = null;
while((txt = bf.readLine()) != null)
array[i++] = txt;
I think its because you are calling readLine() twice. First time in the loop, and then second time when you put it in the array. So, it reads a line at the beginning of the loop (line 1), then first line of code inside the loop (line 2 that you see)
I am use Stream.
Not a. This form only applies to reading text files.
BufferedReader bf = new BufferedReader(fr);
// ...
List<String> lines = bf.lines().collect(Collectors.toList());
I have the following code. What I would like to do is read each line from the BufferedReader directly into a StringBuffer to reduce memory overhead. Once it gets to the end of the data stream I would like it to exit the while loop.
StringBuffer line = new StringBuffer();
URL url = new URL("a url");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
int count = 0;
while(line.append(reader.readLine()) != null){
System.out.println(line.toString());
line.delete(0,line.length());
}
It reads the stream fine but when I get to the end of the stream it returns null and keeps printing null without exiting the loop. Any
This while(line.append(reader.readLine()) != null) is basically the same as saying while(line.append(reader.readLine()).toString() != null) which is never likely to happen.
The other problem you might have, is null is actually being translated to a literal String of "null". That's why it's printing "null", the value isn't actually null - confused yet...
Instead, try something like...
String text = null;
while((text = reader.readLine()) != null){
line.append(text)
System.out.println(line.toString());
line.delete(0,line.length());
}
Updated
While I'm here, I might suggest that you are actually not saving your self anything.
readLine will create String object, which you're putting into a StringBuffer. You're not actually saving any memory, but rather complicating the process.
If you're really worried about creating lots of String objects in memory, then use BufferedReader#read(char[]) instead. Append the resulting character array to the StringBuffer.
Also, unless you need synchronized access to the StringBuffer, use StringBuilder instead, it's faster.
This works perfectly. You just have to catch the NUllPointerException
while(line.append(reader.readLine().toString()) != null){
You could try the same with this for-loop:
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line); // Or whatever
}