Is there a way to place a BufferedReader into a String in one shot, rather than line by line? Here is what i have so far:
BufferedReader reader = null;
try
{
reader = read(filepath);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = null;
String feed = null;
try
{
line = reader.readLine();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null)
{
//System.out.println(line);
try
{
line = reader.readLine();
feed += line;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(feed);
The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.
Reading User's Input using BufferedReader class: By wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line. Here's an example: BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.
Read Characters From a BufferedReader The read() method of a Java BufferedReader returns an int which contains the char value of the next character read. If the read() method returns -1, there is no more data to read in the BufferedReader , and it can be closed. That is, -1 as int value, not -1 as byte or char value.
You could use Apache FileUtils library for the same.
Using the StringBuilder
and read(char[], int, int)
methods would look like this, and is probably the most optimal way to do it in Java:
final MAX_BUFFER_SIZE = 256; //Maximal size of the buffer
//StringBuilder is much better in performance when building Strings than using a simple String concatination
StringBuilder result = new StringBuilder();
//A new char buffer to store partial data
char[] buffer = new char[MAX_BUFFER_SIZE];
//Variable holding number of characters that were read in one iteration
int readChars;
//Read maximal amount of characters avialable in the stream to our buffer, and if bytes read were >0 - append the result to StringBuilder.
while ((readChars = stream.read(buffer, 0, MAX_BUFFER_SIZE)) > 0) {
result.append(buffer, 0, readChars);
}
//Convert StringBuilder to String
return result.toString();
If you know the length of your input (or an upper bound to it) you can read the whole thing to a character array, using read(char[],int,int)
, then use that to build a String. It doesn't matter if your third parameter (len
) is greater than the size, the method will return the number of characters read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With