This question already has answers here:
error message : stream closed
(3 answers)
Closed 6 years ago.
I am calling the name_setter() method from the 'main' by creating an object of customer class to get the input from console and store the name entered in the 'name' variable of the object of the customer class.
import java.io.*;
public class Rental {
public static void main(String[] args) {
customer c = new customer();
c.name_setter(); // calls the method from customer class
}
}
class customer {
String name;
String name_setter() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter the name:"); // executes till here
name = br.readLine(); // stream close error
System.out.println(name);
if (name.length() == 0) {
name = br.readLine();
}
} catch (IOException e) {
System.out.println("" + e);
}
return name;
}
}
the error i am getting is:
java.io.IOException: Stream closed
As Hovercraft Full Of Eels said, this code doesn't cause problem at runtime.
It is probably different from which one rises the exception : java.io.IOException: Stream closed.
Beware : you chain your BufferedReader with the System.in InputStream.
When you close the BufferedReader, it closes the System.in.
For example at the end of this code System.in is closed:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.close();
br = new BufferedReader(new InputStreamReader(System.in));
You should not close the BufferedReader if you want to read again in the System.in.
By deduction, I assume the problem comes from that.
You have the same problem with Scanner instances.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am working on a login for my USB. I know there are other languages that do that better but I am learning Java. I get an error using the IO Console
package access;
import java.awt.Desktop;
import java.io.*;
public class access {
public static void main(String[] args)throws IOException {
BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
Console c = System.console();
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
String user = c.readLine("Username: ");
char pass[] = c.readPassword("Enter password: ");
String uPass = new String(pass);
if(user.equals("yuto") && uPass.equals("abascalesgay")) {
try {
dirToOpen = new File("E:\\encrypted");
desktop.open(dirToOpen);
}
catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
}
}
else {
System.out.println("Credenciales no vĂ¡lidas we, vuelve a intentarlo.");
}
}
}
Error log
Exception in thread "main" java.lang.NullPointerException at
access.access.main(access.java:17)
If you will add this code to your program:
if(c == null)
{
System.out.print("No console available");
return;
}
you will check if your line Console c = System.console(); returns NULL or not.
Currently it is returning NULL as no console was found and the rest of the code can't compile because of it.
If you are running your program through some IDE - it will not work as IDE is not a console!
Go to "cmd.exe"
type "cd" - hit enter..
now type "java " - hit enter
Another alternative to creating your own BufferedReader object from System.in is to use java.util.Scanner like this:
import java.util.Scanner;
Scanner in;
in = new Scanner(System.in);
String s = in.nextLine();
Also if you want to use the System.console() you shouldn't get password with char pass[] but do it through:
String username = console.readLine("Username: ");
String password = new String(console.readPassword("Password: "));
This question already has answers here:
Reading and Writing to a .txt file in Java
(4 answers)
Closed 6 years ago.
This is my code, I can't make it work properly, it gets just the last line from 3 lines total from the first text file and capitalize only that, and I cant figure out why
import java.util.Scanner;
import java.io.*;
public class AllCapitals {
public static void main(String[] args) {
String readLine;
String inFilePath = "/home/file.txt";
String outFilePath = "/home/newFile.txt";
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
readLine.toUpperCase();
String upperC = readLine.toUpperCase();
System.out.println(upperC);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFilePath), "utf-8"))) {
writer.write(upperC);
}
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
}
}
EDIT: Forgot to say the functionallity.
I need to read 3 lines from a normal text file that goes like that
Hello.
How are you ?
Good, thank you !
And the output should be in all CAPS, but I get only the last line "GOOD THANK YOU"
That's because you recreate the output file in each iteration while reading lines from the first.
Create the output file once before you start reading, for example:
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath));
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath), "utf-8"))
) {
while ((readLine = bufferedReader.readLine()) != null) {
String upperC = readLine.toUpperCase();
System.out.println(upperC);
writer.write(upperC);
writer.write(System.lineSeparator());
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
Some other improvements:
Removed a pointless line readLine.toUpperCase(); that did nothing
Add a linebreak for each line, otherwise all the uppercased content would be on the same line
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have learnt about BufferedReader as well as BufferedWriter, so I decided to create a small text processor for the command line (meaning without interface, just in cmd/terminal). It asks a user for document name (Which will then create a file) and then user can type sentences. Each time user presses "enter" button, text is entered into the file and new line is created and then allowing user to type more. At the end, it will display a message saying file is created.
NOW, I have encountered a problem where user would not be able to stop the process of entering data and creating file, because the program kept creating new lines despite entering nothing or quit keyword(which i stated in the code in order to quit the program.)
Here is my original code:
import java.io.*;
class TextProcessor
{
public static void main(String[] args)
{
try
{
System.out.println("Please enter name of the file");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //User input
String file = in.readLine();
BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //Creating file as well as instance for inputting text to the file.
System.out.println("Enter text");
String line = "";
do
{
line = ins.readLine();
System.out.println(line);
writer.write(line);
System.out.println("Second " + line);
writer.newLine();
}
while(line != "quit()");
//while(line != null);
in.close();
writer.close();
System.out.println("Text is created with entered text");
}
catch(IOException e)
{
System.out.println("Error occured");
}
}
}
However, I found a solution to this, which is replacing do-while block with while one:
int counter = 0;
while(counter != 1)
{
line = in.readLine();
writer.write(line);
if(line.equals("quit()"))
{
++counter;
}
else {writer.newLine();}
}
I have a question about this now, why can't I use do-while statement instead of while, even if it seems logical that the program would work? Thank you for reading this!!!!
P.S. I also wonder if I can bring small improvements to this or any other way creating this type of program. Thanks if you give feedback!
Probably the error asked about the most.
Answer can be found here: How do I compare strings in Java?
while(line != "quit()");
must be
while(!line.equals("quit()"));
I am trying to read a from the input using BufferedReader. It works the first time but the second time it is ran I get an exception.
john#fekete:~/devel/java/pricecalc$ java frontend.CUI
> gsdfgd
Invalid command!
> I/O Error getting string: java.io.IOException: Stream closed
I/O Error: java.io.IOException: java.io.IOException: Stream closed
> I/O Error getting string: java.io.IOException: Stream closed
I/O Error: java.io.IOException: java.io.IOException: Stream closed
> I/O Error getting string: java.io.IOException: Stream closed
It just keeps running with that in a loop. I must have missed something.
public static void main(String args[]) {
if (args.length == 0) {
while (!exit) {
try {
exit = processLine(commandLine());
} catch (IOException e) {
System.out.println("I/O Error: " + e);
}
}
System.out.println("Bye!");
} else if (args.length == 1) {
String line = new String(args[0]);
processLine(line);
} else {
String line = new String(args[0]);
for (String np : args) {
line = new String(line + " " + np);
}
processLine(line);
}
}
static private String commandLine() throws IOException {
String str = new String();
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("> ");
str = new String(br.readLine());
str = str.trim();
} catch (IOException e) {
System.out.println("I/O Error getting string: "+ str + " " + e);
throw new IOException(e);
}
return str;
}
It really all seems to be about commandLine() not working so I've just included that and main.
Yes, you're closing the stream here:
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
That try-with-resources statement will close the BufferedReader at the end of the block, which will close the InputStreamReader, which will close System.in.
You don't want to do that in this case, so just use:
// Deliberately not closing System.in!
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
...
}
It's still possible that this won't quite behave as you want though, as the BufferedReader could potentially consume (and buffer) more data. You'd be better off creating the BufferedReader once (in the calling code) and passing it to the method.
Oh, and I suggest you get rid of this:
String str = new String();
There's no need for it at all. This would be better:
String str = "";
But even then, it's a pointless assignment. Likewise you don't need to create a new String from the one returned by readLine(). Just use:
return br.readLine().trim();
... within the try block. Also, there's no point in logging str within the catch block, as it's going to be empty - the IOException will only be thrown when reading the line...
im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!
This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}
If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}
Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)