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.
Related
I'm trying to rename the file that my program is outputting, but no matter what name i'm trying to change it to, it is stuck with the first name i listed which is "output.txt". I rename it to output1. txt and it still gives me output.txt could someone help with this?
public class Assignment2 {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Sample command: java Assignment2 input.txt");
System.exit(0);
}
try {
Scanner scanner = new Scanner(new File(args[0]));
FileWriter fw = new FileWriter("output1.txt");
int i = 1;
while (scanner.hasNext()) {
System.out.println("Matrix #" + i);
processMatrix(scanner, fw);
i++;
System.out.println("");
fw.write(System.lineSeparator());
}
scanner.close();
fw.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
Logger.getLogger(Assignment2.class.getName()).log(Level.SEVERE, null, ex);
}
}
From what I can see there is nothing wrong with your code.
So the only problem I can think of, is you are not building/compiling the file and therefore you are stuck on a older version of that file.
I don't know what technology stack you are using, but a still way to check this since its java, hopefully you got the environment variables configures. Just go to your terminal, to the file folder and:
javac Assignment2.java
java Assignment2
You can also tell me which IDE you are using, or how you are building/running your code.
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)
I am trying to delete a file from a directory using Java with the following code:
static String deleta ="C:\\res\\in\\CANteste2.xml";
.
.
.
Boolean file = new File (deleta) .delete();
System.out.println ("file:" + file);
Permissions: http://imgur.com/a/dVPPW
But it returns always false with no errors
You should use try and catch code for deleting the files
if using java 7 then use Files API
or try to check the File exists() method before deleting file
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
I see some compilation errors in the code snippet.
System.out.println (file:" + file);
This statement will not compile. Probably you meant:
System.out.println ("file: "+file);
The three lines will not be present in a single method. Reason is that you have declared the deleta variable as static. This means that you have to make it Class level. Thus, if you make deleta and file as Class level variables, you cannot have the System.out.println ("file: "+file); in the Class Level. The Syso statement should be in a method.
Finally your code should look like:
public class Test {
static String deleta = "C:\\res\\in\\CANteste2.xml";
Boolean file = new File(deleta).delete();
public static void main(String[] args) {
Test test = new Test();
test.print();
}
public void print() {
System.out.println("file: " + file);
}
}
This code will return TRUE if the file was PRESENT and is now DELETED. It will return FALSE if the file is not found in the directory.
So the first instance you will run the code, you will get the output as TRUE (if the file is present). From the second instance onwards, you will get the output as FALSE, as it has already been deleted!
I am building an optimization into a JPEG-Encoder written in Java. To do my benchmark i want to extract the orginal code and the optimized code into separated jars. Each jar has to take two arguments. The first on for the file name and the secound for the repeat of the compression of the jpeg.
public static void main(String[] args) {
String filepath = args[0];
try {
int times = Integer.getInteger(args[1]);
runBenchmark(filepath, times);
} catch(IOException | NumberFormatException ioe) {
System.out.println("Your arguments are Wrong! Use the follow order!");
System.out.println("1. Argument must be the filename of the image.");
System.out.println("2. Argument must be a number to repeat the compression.");
}
}
This is my main, witch handle my args. I cant run the arguments on IntellJ . Even if I compile it the a jar, i cant pass my arg2.
I passed two arguments via configuration in intellj and i get a NullPointerException. So i tried to figure out if my java can take two arguments. I wrote a simple main in vim and compiled ran it with two args and worked. I repeated this in a new Project in intellj.
This is working. But why?
You have to check if the parameter is a int or not.
Use Integer.parseInt() and a try-catch block to inform the user if a failure happen.
int times = 0;
try {
times = Integer.parseInt(args[1]);
} catch (Exception e) {
System.out.println("failure with a parameter");
}
I changed the method to Integer.parseInt(string) and now it works. It was the Integer.getInt() it . I thought i had now 2. arg because I get the NullPointerException.
Now it work with this code.
public static void main(String[] args) {
try {
String filepath = args[0];
int times = Integer.parseInt(args[1]);
runBenchmark(filepath, times);
} catch (NumberFormatException nfe) {
System.out.println("2. Arg must be an number");
} catch (IOException ioe) {
System.out.println("File not found.");
} catch(Exception e) {
System.out.println("Your arguments are Wrong! Use the follow order!");
System.out.println("1. Argument must be the filename of the image.");
System.out.println("2. Argument must be a number to repeat the compression.");
}
}
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