Java: Read file: no good output - java

I updated the code but I get still a null value in my textfield. In the console I can see everything from the file WandelaarBestand. Maybe It has something to do with converting number to string.But when I wan't to dat that with int getal I get nothing. Without int getal I get a Null value in my textfield but I can still see everething from my file in my console.
Here you can find my updated code.
public class geefInfo implements ActionListener {
public void actionPerformed(ActionEvent e) {
BufferedReader in;
String regel="";
int getal;
try {
in=new BufferedReader(new FileReader("WandelaarBestand.txt"));
while((regel=in.readLine())!=null){
getal=Integer.parseInt(regel);
System.out.println(regel);
}
in.close();
} catch (FileNotFoundException e6) {
e6.printStackTrace();
System.out.println("kan file niet vinden");
} catch (IOException e7) {
e7.printStackTrace();
System.out.println("fout bij lezen of sluiten file");
}
info.setText(""+regel);
}
}

in your second try block you print out the line - so far so good.
But your line:
String naam2=naam.getText();
does not make any sense, because naam is never set and in the follwing if statement you just use naam2, which is null as well.
Also try to close your reader, it can get messy if you don't.
Hope that helps a bit

Related

Call a class whose name is in a string

I'm trying to call a class whose part of the name is included in a string obtained by reading console input.
static void menu() {
System.out.println("Choose a menu:");
System.out.print("\n");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String nome = null;
try {
nome = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("\n");
System.out.println("Opening: " + nome);
System.out.print("\n");
String funzione = nome + ".funzione();";
try {
Runtime.getRuntime().exec(funzione);
} catch (IOException e) {
System.out.println(funzione);
e.printStackTrace();
}
Basically, if I write "print", I'd like to execute print.function(); which is called later in the program. The code works but it also outputs an error java.io.IOException: Cannot run program "print.function();": error=2, No such file or directory, yet print.function(); gets executed anyway.
To be clear, I am intentionally following this method rather than a switch case.
I think I'm executing the process in a wrong way, could anyone highlight me where? Many thanks.

How to get error line number using try/catch in java?

I want to find out the error line number using try and catch. I tried to get some information from How to get error line number of code using try-catch, but it didn't help since I use different language.
Now, I am getting java.lang.NumberFormatException: For input string: "" when I do
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
}
I tried printing e.getStackTrace()[0].getLineNumber()); as well, but it seems like it's not showing the correct error line number. Is there any way I can get it easily? I have a pretty big file and I don't think I'll be able to go over line by line to figure out what's wrong.
Thanks!
If you use a Logger library, it can print the stack trace in debug mode that points to the line number. else printStackTrace() is your friend.
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
e.printStackTrace(); // This will give line number
}
package com.ms.common;
public class Run {
public static void main(String[] args) {
try {
int value = 5;
int divider = 0;
int result = value / divider;
} catch (Exception e) {
System.out.println(e.getStackTrace()[0]);
}
}
}
Error at Run.java at line# 11
com.ms.common.Run.main(Run.java:11)

Try catch error

I have these 2 methods to read a number of integers from a file and insert them in a tree. It works fine if the file is found but if the file is not found it doesn't print "File not found". Why is it not going into the catch statement? Thanks!
public static void openF(Tree myT)
{
try
{
x=new Scanner(new File("Number.txt"));
readF(myT);
}
catch(Exception e)
{
System.out.println("File not found");
}
}
// to read from the file
public static void readF(Tree myT)
{
while(x.hasNext()) //keeps going till it reaches the end of file
{
int a =x.nextInt();
myT.insert(a); //insert in tree
}
}
I tested a simplified version of your code:
public static void main(String[] args) {
try {
new Scanner(new File("H:\\Hello.txt"));
System.out.println("The file exists.");
} catch (Exception e) {
System.out.println("File not found: " + e.getMessage());
}
}
When the file exists, it prints The file exists.. If not, it prints File not found: H:\Hello.txt (The system cannot find the file specified).
So no, the catch block is running as expected. The error is somewhere else in your code, but given that you're not providing the full code, nor a part which actually compiles (x is not declared), there is no way for us to guess where the actual error is.

Trying to output a string variable to a .txt file within an IF statement. - Java

I'm pretty new to java and i still have alot to learn. I'm trying to output the data within a variable to a text file, and I'm not sure why this will not work. Could anyone help me out?
if ("Y".equals(output_to_file)) {
System.out.print("You selected Yes");
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("filename.txt"));
out.print(first_input);
}
finally {
if (out != null) out.close();
}
}
else System.out.print("You selected No");
"(new FileOutputStream("filename.txt"))" is underlined red, and it says: Unhandled exception: java.io.FileNotFoundException
Thanks for your help!
Anytime you're doing file operations, there is the possiblity that a FileNotFoundException will be thrown. Therefore, Java wants you to tell it what to do in the event that one is thrown. Thus, you need to add a catch clause for the possible FileNotFoundException. You already have a try block, so you simply need to add a catch clause before your finally clause:
try {
out = new PrintStream(new FileOutputStream("filename.txt"));
out.print(first_input);
}
catch(FileNotFoundException e) {
//do something in the event that a FNFE is thrown
}
finally {
if (out != null) out.close();
}
}

Java io handle is invalid exception

I have a function that reads from the console using readPassword(). This function is called several times in one program iteration. However, I keep getting a java io exception once it gets to the readPassword() line. I noticed when i removed the close() statement from the finally-clause this error disappears. Why does this happen and when should I properly close the reader?
public void Func()
{
Console console = System.console();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
if (console == null)
System.out.println("Error!");
try
{
char[] pwd = console.readPassword();
String password = new String(pwd);
System.out.println("PW: " + password);
String input = reader.readLine();
System.out.println("UserNm: " + input);
} catch (IOException e) {
System.out.println("IO EXCEPTION");
} finally {
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
System.out.println("error");
}
}
}
return null;
}
Thanks in advance for the help!
There's only one console, and there's only one System.in. If you close it, then you can't read from it anymore! You don't need to close that BufferedReader, nor should you. That whole finally block can and should just go away.
On closer reading, I don't even see why you're creating the BufferedReader in the first place -- it seems to have no function. Just delete all the code that deals with it!
You don't need any reader here, just use the Console instance.
public String Func() {
Console console = System.console();
if (console == null)
throw new IllegalStateException("No console available");
try {
String username = console.readLine("Username: ");
String pwd = new String(console.readPassword("Password: "));
return pwd;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Edited with your question edit. Just use the Console class, it can read/write, you don't need any reader/writer.
Use something like java.util.Scanner instead and as other people say don't worry about ever trying to close system.in.
So much cleaner:
Scanner in = new Scanner(System.in);
String password = in.nextLine();
String username = in.nextLine();
No tidy up/exception handling required.
You should not close your Console. Keep it open until your program does no longer need to read from it.

Categories