I am working on small program where user inputs text in standard input and then this text is returned with proper alignment.
My main block of code where input is being read line by line:
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
for (String nextLine, line = br.readLine(); line != null; line = nextLine) {
nextLine = br.readLine();
// Work with "line"
}
}
catch (IOException ex) {
System.exit(-1);
}
}
But input is never read all. Always last line is missing and line is never null. After little debugging I found out that br.readLine() on line nextLine = br.readLine(); doesn't return anything (literally it doesn't return anything. No exception is thrown though.) and program keeps running but is not executing any other lines of my code. I also tried reading from file and this problem doesn't occur.
That is probably because readLine() blocks until a new line is available or the stream reaches EOF (which never happens when you read from System.in).
You never get the last input because your loop always processes the previously read line.
Try this:
for (String line; (line = br.readLine()) != null;)
and break from this loop when you've read all the input you need, ex:
if(line.equals("finish")){
break;
}
When your input comes from standard input, you have to let your program know when the input ends. Otherwise it will keep waiting for the next input to be entered.
Therefore you should decide on some character or String that would mark the end of the input.
For example, here typing done would end the loop :
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
for (String nextLine, line = br.readLine(); line != null && !line.equals("done"); line = nextLine) {
nextLine = br.readLine();
// Work with "line"
}
}
catch (IOException ex) {
System.exit(-1);
}
}
Related
I am facing some problem while reading the contents of file.
Although program is reading contents, it is skipping odd line data from file.
Example of file:
Czech Republic____06092015_091108
France____06092015_060256
Greece____06092015_073528
Hungary____06092015_093424
India____06092015_120741
Indonesia____06092015_140940
Kazakhstan____06092015_095945
Mexico____06092015_061522
Turkey____06092015_100457
But the output is:
java.io.DataInputStream#1909752
France____06092015_060256
Hungary____06092015_093424
Indonesia____06092015_140940
Mexico____06092015_061522
I don't understand why it is giving output as in this format.
I have line separator in input file, can it be causing the problem?
public class tst {
// Main method
public static void main(String args[]) {
// Stream to read file
FileInputStream fin;
int k = 0;
try {
// Open an input stream
fin = new FileInputStream(
"C:/Users/BOT2/Desktop/MC_WIth_DATA_Files.txt");
DataInputStream in1 = new DataInputStream(fin);
// Read a line of text
System.out.println(new DataInputStream(fin));
// Close our input stream
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
while (br1.readLine() != null) {// System.out.println(k);k++;
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
// Catches any error conditions
catch (IOException e) {
System.err.println("Unable to read from file");
System.exit(-1);
}
}
}
You have two errors. First, you print out the dataStream object for some reason. Get rid of :
// Read a line of text
System.out.println( new DataInputStream(fin) );
Next, you throw away lines of text. Try this instead:
String line;
while ((line = br1.readLine()) != null){
System.out.println(line);
}
The first line is printed by:
System.out.println( new DataInputStream(fin) );
it gives you te result of new DataInputStream(fin).toString()
The next lines are printed in this format, bacause you read two lines per loop:
first line while (br1.readLine() != null){ and second line: System.out.println(br1.readLine()); }
So you have to change your code to:
String line;
while ((line =br1.readLine()) != null){//System.out.println(k);k++;
System.out.println(line );
}
br1.close();
fin.close();
The problem is here
while (br1.readLine() != null){
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
When you call br1.readLine() it reads out the current line and move the cursor position to point to the next line. You are calling this method twice causing you to skip alternative lines. You should call readLine() only once per iteration.
i suggest cleaner code so you and whoever reads it will understand immediately what you are doing.
Try this :
Scanner read;
try{
read=new Scanner(new FileReader("your path"));
while(read.hasNext()){
System.out.println(read.nextLine);
}
read.close();
}
catch(FileNotFoundException e){
}
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 need to be able to read each line of the file for multiple arguments, hence the for loop. After the first one, it does not seem to be reading them anymore, seems to skip the try statement. Any ideas? I'm sure Its something silly I am missing but have been playing about with it and unfortunately time is not on my side.
for (int j = 0; j < ags.length; j++){
try{
String nameFromFile = null;
BufferedReader InputReader = new BufferedReader(new InputStreamReader(System.in));
while ((nameFromFile = InputReader.readLine()) != null) {
// Do stuff
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You appear to have two sources you want to compare System.in and args I suggest you read these individually and then compare them.
Set<String> fromInt = new HashSet<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
for(String line; (line = br.readLine()) != null;)
fromIn.add(normalise(line));
}
// compare argsList with fromIn.
e.g.
for(String arg: args) {
if (fromIn.contains(normalise(arg))) {
// something
} else {
// something else
}
}
I need to be able to read each line of the file
What file? You're reading from System.in:
BufferedReader InputReader = new BufferedReader(new InputStreamReader(System.in));
Your code will block at this line until you enter something at the console.
You do not read a file, bu the System.in stream.
Every stream has an internal pointer, so the stream nows, which line was read at last.
If the System stream was read once, the pointer is pointing to the end of the stream.
As long as the stream is not reset, the read command will not return anything.
try
InputStream.reset()
or even better, only read the Stream once and cache the result! This is faster and safe, because the Stream input can change during iteration.
Your code will never exit from while loop.
while ((nameFromFile = InputReader.readLine()) != null)
In above loop it will print only one time and at the end of the file it will not be out of the while loop . That's why you are getting only one time output. Since it is not exited from while loop it does not go back into for loop. readLine() return the string and it is terminated by "\n" or "\r\n". Change as below and you will be able to read as ags.length
while ((nameFromFile = InputReader.readLine())=="\n")
I have problem with reading data from file.
In each line (except first) first char is lost!
Maybe i have troubles with coding, but i try to set UTF-8, UniCode, ANSI, and result is fast the same...
Code:
try (FileReader fr = new FileReader("123.txt")) {
// create a buffer for file reader
BufferedReader br = new BufferedReader(fr);
do {
input = br.readLine();
System.out.println(input);
} while (br.read() != -1);
} catch (IOException ex) {
System.out.println("IOex : " + ex);
}
Console:
2
FFFFFF
FAF9F5
FDBCA1
FBCCB8
but must be:
2
#FFFFFF
2
#FAF9F5
6
#FDBCA1
9
#FBCCB8
9
it only works, when i put slashes before lines.
2
\#FFFFFF
\2
\#FAF9F5
\6
\#FDBCA1
\9
\#FBCCB8
\9
What can it be?
Thanks!
The problem is with the end of your do loop:
do {
input = br.readLine();
if (input.endsWith("\n")) {
input = input.substring(0, input.indexOf("\n"));
}
System.out.println(input);
} while (br.read() != -1);
You're calling read() which will read the first character of the next line - but you're only using that to check for whether the file has ended. (Notice how you've got the first character of the first line, because there you're calling readLine without previously calling read.)
This would work fine - and be simpler:
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
readLine returns null when you've reached the end of the data. Note that you don't need to check for input containing \n as you're already reading one line at a time, and \n is deemed to be a line separator.
If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.