Read all lines with BufferedReader
One line of code using Java 8:
line = buffer.lines().collect(Collectors.joining());
How to use BufferedReader to read content in DataInputStream
You can't. If you use writeUTF()
at one end, you have to use readUTF()
at the other end.
You just have to decide which API you're going to use, instead of trying to mix and match them.
how to use BufferedReader class to take character and string input from user?
By strange output do you mean this?
enter the Character:
a
enter the string:
entered string:
entered Character: a
It's not a strange output, because BufferedReader#read
reads exactly one character and BufferedReader.readLine
reads everything from the beginning of the line to newline character (\n
).
When you press Enter, you're pushing \n
to STDIN. So, in this example, my input was a\n
. First read
recognized letter 'a' and then readLine
read '\n' symbol, thus saving empty string to str
.
Fix
To fix this, you need to omit the newline character by calling read
again.
InputStreamReader InputObj = new InputStreamReader(System.in);
BufferedReader BufferObj = new BufferedReader(InputObj);
System.out.println("enter the Character: ");
char c = (char)BufferObj.read();
BufferObj.read(); // omit '\n' going after previous char
System.out.println("enter the string: ");
String str = BufferObj.readLine();
System.out.println("entered string: "+str);
System.out.println("entered Character: "+c);
Running this code gives the next output
enter the Character:
a
enter the string:
string
entered string: string
entered Character: a
Confused on how to use BufferedReader for reading arraylist of User objects
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
}
Well, that code only reads a single line since you only ever invoke the readline() method once.
The code should be something like:
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
currentLine = br.readLine();
}
And since your data for the User
is contained in a single line (since you just save the toString() of your User class) you will need to parse the data into its individual tokens probably by using the String.split(...)
method.
Of course your readToFile(...) method won't really do anything because you define the ArrayList locally and don't return any data from the method so the rest of your class can't access the data.
confused with buffered reader in java
Your BufferedReader
uses the InputStreamReader
with System.in
. The BufferedReader
uses the read()
method from InputStreamReader
to read the data from the standard input stream System.in
. Now lets look into the API for this read()
method.
[...] This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
Blocking means in this context waits for user to input data throu the console confirming with the Enter Key.
With that in mind lets examine your cases.
1. int b= br.read();
Nothing is already typed, so this method blocks until user typed something and then prints the ascci value of first character.
2. String a = br.readLine();
Nothing is already typed, so this method blocks until user typed something and then prints the whole line.
3.
int b= br.read();
Lets image user typed a
confirming with Enter Key that means the input is a\n
. Now read()
reads the first character which is a
.
String a = br.readLine();
This read()
call will not block and ask for user input because there is unconsumed input left \n
. So readLine()
will read \n
.
4.
String a = br.readLine();
User is asked for input which is confirmed with Enter Key. And the whole line will be read.
int b= br.read();
There are no unconsumed data left, because readLine()
already has read the whole line including \n
character. So this read()
call blocks and user is asked for input.
java: how to use bufferedreader to read specific line
I suggest java.io.LineNumberReader. It extends BufferedReader and
you can use its LineNumberReader.getLineNumber();
to get the current line number
You can also use Java 7 java.nio.file.Files.readAllLines
which returns a List<String>
if it suits you better
Note:
1) favour StringBuilder over StringBuffer, StringBuffer is just a legacy class
2) contents.append(System.getProperty("line.separator"))
does not look nice
use contents.append(File.separator)
instead
3) Catching exception seems irrelevant, I would also suggest to change your code as
public static String getContents(File aFile) throws IOException {
BufferedReader rdr = new BufferedReader(new FileReader("aFile"));
try {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
} finally {
rdr.close();
}
}
now code looks cleaner in my view. And if you are in Java 7 use try-with-resources
try (BufferedReader rdr = new BufferedReader(new FileReader("aFile"))) {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
}
so finally your code could look like
public static String[] getContents(File aFile) throws IOException {
try (LineNumberReader rdr = new LineNumberReader(new FileReader(aFile))) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (String line = null; (line = rdr.readLine()) != null;) {
if (rdr.getLineNumber() >= 1500) {
sb2.append(line).append(File.pathSeparatorChar);
} else if (rdr.getLineNumber() > 500) {
sb1.append(line).append(File.pathSeparatorChar);
}
}
return new String[] { sb1.toString(), sb2.toString() };
}
}
Note that it returns 2 strings 500-1499 and 1500-2000
How to use BufferedReader in a try catch?
1) The errors are simple, firstly you're supposed to use new FileReader
(with lowercase n
) rather than New FileReader
(with uppercase N
).
2) you're closing the else
block before attaching the catch
handlers to the try
block.
I have now corrected both issues and the code below should compile.
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
br.close();
}catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
Related Topics
Do Not Use System.Out.Println in Server Side Code
Passing an Array or List to @Pathvariable - Spring/Java
What Is the Time Complexity Performance of Hashset.Contains() in Java
Spring Security's Securitycontextholder: Session or Request Bound
Set Specific Precision of a Bigdecimal
Steganography in Lossy Compression (Java)
Centering Text in a Jtextarea or Jtextpane - Horizontal Text Alignment
Getting Nosuchmethoderror:Javax.Servlet.Servletcontext.Getvirtualservername()
How to Convert a Java Object to Xml with Open Source APIs
How Can "This" of the Outer Class Be Accessed from an Inner Class
Concurrent Threads Adding to Arraylist at Same Time - What Happens
What Code Does the Compiler Generate for Autoboxing
Maximum Size of a Method in Java
What Is the Java Equivalent of Sscanf for Parsing Values from a String Using a Known Pattern