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: "));
Related
I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.
From the command line, it should be fine though. Sample:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
Run this just with java:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).
Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LoopingConsoleInputExample {
public static final String EXIT_COMMAND = "exit";
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
while (true) {
System.out.print("> ");
String input = br.readLine();
System.out.println(input);
if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
System.out.println("Exiting.");
return;
}
System.out.println("...response goes here...");
}
}
}
Example output:
Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.
I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.
It introduces an abstraction layer similar to the one proposed by McDowell.
If System.console() returns null, the library switches to a Swing-based console.
In addition, Text-IO has a series of useful features:
supports reading values with various data types.
allows masking the input when reading sensitive data.
allows selecting a value from a list.
allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).
Usage example:
TextIO textIO = TextIoFactory.getTextIO();
String user = textIO.newStringInputReader()
.withDefaultValue("admin")
.read("Username");
String password = textIO.newStringInputReader()
.withMinLength(6)
.withInputMasking(true)
.read("Password");
int age = textIO.newIntInputReader()
.withMinVal(13)
.read("Age");
Month month = textIO.newEnumInputReader(Month.class)
.read("What month were you born in?");
textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
"was born in " + month + " and has the password " + password + ".");
In this image you can see the above code running in a Swing-based console.
Use System.in
http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html
Can someone please explain to me why I'm getting the catch error ?
I am trying to read values (numbers) from the file I passed in args.
And I do not quite understand where the problem comes from.
import java.util.Scanner;// Import the Scanner class to read text files
import java.io.File;// Import the File class
import java.io.FileNotFoundException;// Import this class to handle errors
import java.io.*;
public class main extends GeneralMethods {
public static void main(String[] args) {
if (args.length <= 1 || args.length > 2) {
println("Error, usage: software must get two input files");
System.exit(1);
}
String file_name1 = args[0]; // data to insert
String file_name2 = args[1]; // data to check
File data_to_insert = new File(file_name1);
File data_to_check = new File(file_name2);
Scanner input = new Scanner(System.in); // Create a Scanner object
println("Enter hashTable size");
int hashTable_size = input.nextInt(); // Read hashTable_size from user
println("Enter num of hashing function");
int num_of_has = input.nextInt(); // Read num of hashing from user
hashTable T = new hashTable(hashTable_size);
println("hashTable before insert values\n");
T.printHashTable();
input.close();
int i = 0;
try {
input = new Scanner(data_to_insert);
String data;
while ((data = input.next()) != null) {
T.set(i, Integer.parseInt(data));
i++;
}
input.close();
} catch (Exception e) {
System.out.println("\nError: Reading, An error occurred while reading input files. Check your input type");
e.printStackTrace();
}
T.printHashTable();
}
}
this is my output
Which prints the catch error
hashTable before insert values
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Error: Reading, An error occurred while reading input files. Check your input type
java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at main.main(main.java:36)
[1,2,3,4,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
In this line,
while ((data = input.next()) != null)
The next() method of Scanner does not return null if it has no more data, instead it throws the NoSuchElementException you are getting.
Use this instead to check for more data:
while ((input.hasNext()) {
data = input.next();
//...
}
Method hasNext() returns true or false as you would expect.
I need to make a simple Java program that writes it output to the cmd (the Command Prompt) window and reads user's input from there.
When I run the code from the IDE using the standard System.out.println it presents the output on the IDE (I use intelliJ) console view.
I guess this is a simple question and there are already answers for it here but I made several searches and did not find appropriate resolution.
That's it. your program now will output to cmd if you run it using cmd instead of IDE.
For input you can use scanner to read user input. or simply let user enter them all before running the program and include the args of main method in your logic to process user's input.
demo for u :)
public class testCMD {
public static void main(String[] args) {
testCMD obj = new testCMD();
System.out.println("Press command here:");
Scanner keyboard = new Scanner(System.in);
String command = keyboard.next();
//String command = "msconfig";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
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.
I am trying to make a login/password program which asks if you have an account and you can also make one.
By account I mean the program will give you a random 8 digit number.
I also have a FileWriter which creates a file based on the ID you were given. And I have a FileReader which will eventually read what you previously exported to your file so you can update it.
The problem I have is that when I ask the user if they have an account already, if they say yes it will ask the user for their UserID.
My plan was that when it read your UserID it would scan the folder I have my .java file saved in and look for a .txt file with the same name as your UserID. For example, if you make an account and the UserID it gives you is 12345678 it will create a file named 12345678 and then when you input you UserID it will scan to see if that file exists.
Currently The problem that occurs is the it prints
Error File Not Found(the catch String I wrote)
even though I have that file in the folder.
I think there is something wrong with how I am comparing to see if the UserID matches any file name.
The "Login" class.
import java.awt.*;
import hsa.Console;
import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Login
{
static Console c;
static Login player1;
public static void main (String[] args)
{
player1 = new Login ();
player1.FileReaderTest (25756326);
//player1.Userlogin (); //I think it has something to do with this
} // main method
public void Userlogin (File input)
{
c = new Console ();
Random rand = new Random ();
c.println ("Hello do you have an account?");
String Q1 = c.readLine ();
Q1 = Q1.toUpperCase ();
if (Q1.equals ("YES"))
{
c.println ("Please input your User ID");
int login = c.readInt ();
if (String.valueOf(login).equals (input))//I think it has something to do with this
{
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
}
else if (Q1.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (99999999);
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
}
while (!Q1.equals ("YES") && !Q1.equals ("NO")) //While Q1 != YES || NO
{
c.println ("Please Answer the question with Yes or No");
c.println ("Hello do you have an account?");
String Q2 = c.readLine ();
Q2 = Q2.toUpperCase ();
if (Q2.equals ("YES"))
{
c.println ("Ok lets start");
break;
}
else if (Q2.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (89999999) + 10000000;
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
break;
}
} //While Q1 != YES || NO
} //Public void Main
public void FileReaderTest (int UserID)
{
File input = new File (String.valueOf (UserID));
player1.Userlogin (input);
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
public void FileCreation (int UserID)
{
try
{
Writer writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (String.valueOf (UserID)), "utf-8"));
}
catch (IOException ex)
{
}
}
} // Login class
So, you have a File input, and you want to compare the name of the file, so you instead want
String.valueOf(login).equals (input.getName());
If you are getting an error on
File input = new File (String.valueOf (UserID));
then note: "2.txt", for example, is very different than a file named just "2" (which is worth mentioning because Windows hides file extensions by default)
And if you aren't giving the full path to the file, then that file has to be in your "classpath", which if you don't understand, better to give the full path to the file.
FileNotFound is not thrown after a comparison but by your FileReader when it is created. FileReader tells you that there is not file named as such. Since you said that you did create the file, there can be a few explanations:
Maybe the file you created is in the wrong folder. The default folder for a java program is the project folder. Make sure that you have your file in the right folder. Else you can give the full path as an argument for the FileReader: "/my/full/path/filename.extension".
It can also be a problem of extension. If you are using a Windows OS, the extension may be hidden in the file explorer. Right clic on your file and check whether there is such an extension (ex: ".txt")
Eventually you can open the file with a FileWriter under Java, and try to create the file within your program. You will see more easily which file Java is trying to access and it will help you identify your issue.
Since you have mentioned that you need to create the text file associated with the UserId, I would suggest adding the ".txt" in the FileReaderTest class. Something similar to this :
File input = new File (String.valueOf (UserID)+".txt");
Or more conveniently
File input = new File (Integer.toString(UserID)+".txt");
I think this solves your query.