I'm getting a file not found exception from this code even though it's within the try catch statement and I'm not sure what's wrong, the file is within the project folder and is called 'someFile.txt'. This is the main method:
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no arguments given");
return;
}
double FRE = sortFile(args[0]);
System.out.println("Readability of file " + args[0] + "= " + FRE);
}
And this is the sortFile method where the exception occurs:
public static double sortFile(String FileName) {
int nWords = 0;
int nSyllables = 0;
int nSentences = 0;
File text = new File(FileName);
try {
Scanner sc = new Scanner(text);
while (sc.hasNext()) {
contents.add(sc.next());
++nWords;
}
sc.close();
for (String e : contents) {
getNumSyllables(e);
}
} catch (FileNotFoundException e) {
System.out.println("The file" + FileName + "could not be opened.");
e.printStackTrace();
}
double FRE = getFRE(nWords, nSyllables, nSentences);
return FRE;
}
Thanks for any help :)
well, the file does not exist in that location. Try to add
System.out.println(text.getAbsolutePath())
to see where the file is expected. Note, when you provide a relative path (e.g. some/path/filename.ext), this is relative to the working directory. The working directory is the folder your java program is started in.
If you're using an IDE (e.g. Eclipse, IntelliJ, Netbeans) you can define the working directory in your run configuration.
See:
Javadoc of java.io.File to learn how relative paths work inside a Java environment: http://docs.oracle.com/javase/7/docs/api/java/io/File.html
working dir: Getting the Current Working Directory in Java
I'm getting a file not found exception from this code even though it's
within the try catch statement
The try-catch does not prevent the Exception from being thrown. It merely executes the code in the catch block when an Exception is thrown, and you are just printing the stack trace in the catch block, which is what usually printed anyways on uncaught exceptions.
To resolve your actual issue, first try passing the full path to the file, verify that it works and then use Tim's answer to debug your absolute path.
Try launching your program with the absolute path.
java yourclassname absolutepath_to_someFile.txt
Related
I am building an application that takes input through an XML file and executes a number of operations based on it. I know the application works, because I can supply a file for an XML directly in code and it will run as it should.
The problem arises when I try to pass the path to an XML file in through the commandline args of the packaged .jar.
My main looks like this:
public static void main(String[] args) {
LogWriter.openWriter();
LogWriter.log("Main start.");
Controller controller = new Controller();
LogWriter.log("Controller created.");
List<Parameters> parameters = new ArrayList<Parameters>();
for (int i = 0; i < args.length; i++) {
LogWriter.log("Got arg: " + args[i]);
File file = new File(args[i]);
LogWriter.log("Parameter file: " + file.getAbsolutePath());
if (file.exists()) {
LogWriter.log("File exists. Getting parameters.");
Parameters para = controller.getParameters(file);
LogWriter.log("Attempting to add parameters.");
parameters.add(para);
LogWriter.log("Added parameters.");
} else {
LogWriter.log("File is not valid.");
}
}
}
The script I use to run it looks like this:
java -jar PDFRedacter.jar C:\Users\je\Downloads\XMLConfig.xml
What is really strange about is, is that it only fails when I give it a valid file. If I supply an invalid file, it runs, and logs that the file is invalid, and as mentioned it also runs if I input a valid file directly in the code.
However, with a valid path written in the batch, not even the first 'Main start' is logged, so the code does not run at all. Is this perhaps some access problem?
EDIT: The logger is not my issue, it works as intended both with and without a valid file. Example of 'Invalid file' log:
Main start.
Controller created.
Got arg: C:\Users\je\Downloads\XMLConfig
Parameter file: C:\Users\je\Downloads\XMLConfig
File is not valid.
To clarify, the issue is not actually reading a file. The issue is, that when I supply a valid file through the batch script, it seems like my code doesn't run at all.
FINAL EDIT:
It turns out the problem was simply with the packaging of my .jar, lacking a dependecy. As someone else suggested, my logger was only flushing at the very end of excecution, and that's why it didn't write anything. Thanks for your comments.
As Thomas suspected, there must be another reason for the program to fail, because your function should work. If you reduce it to detecting if a file exists and once you made shure it works, add the parameter list, controller and logger one after another you may find the reason for the failure.ยด
Here is the example I tested - and it works perfectly for all existing files or directories.
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("Got arg: " + args[i]);
File file = new File(args[i]);
System.out.println("Parameter file: " + file.getAbsolutePath());
if (file.exists()) {
System.out.println("File exists. Getting parameters.");
} else {
System.out.println("File is not valid.");
}
}
}
I try to run ParallelTopicModel class from mallet, i'm using NetBeans to compile it, but when i run the code i get this error statement:
Couldn't open cc.mallet.util.MalletLogger resources/logging.properties file.
Perhaps the 'resources' directories weren't copied into the 'class' directory.
I haven't change any code anyway, still use the original from the class:
public static void main (String[] args) {
try {
InstanceList training = InstanceList.load (new File(args[0]));
int numTopics = args.length > 1 ? Integer.parseInt(args[1]) : 200;
ParallelTopicModel lda = new ParallelTopicModel (numTopics, 50.0, 0.01);
lda.printLogLikelihood = true;
lda.setTopicDisplay(50, 7);
lda.addInstances(training);
lda.setNumThreads(Integer.parseInt(args[2]));
lda.estimate();
logger.info("printing state");
lda.printState(new File("state.gz"));
logger.info("finished printing");
} catch (Exception e) {
e.printStackTrace();
}
}
I am very new to mallet, so I don't know what's that mean, and how can I fix it? Any help would be appreciated.
Mallet is looking for a Java property java.util.logging.config.file. If it doesn't find it, it looks for the resources/logging.properties file, and if it doesn't find that it throws the error you saw.
The default Mallet logging file is at https://github.com/mimno/Mallet/blob/master/src/cc/mallet/util/resources/logging.properties.
You'll need to consult NetBeans documentation for how to set the Java property.
The following program has the purpose of creating a directory,
folderforallofmyjavafiles.mkdir();
and making a file to go inside that directory,
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
There are two problems though. One is that it says the directory is being created at the desktop, but when checking for the directory, it is not there. Also, when creating the file, I get the exception
ERROR: java.io.FileNotFoundException: folderforallofmyjavafiles\test.txt (The system cannot find the path specified)
Please help me resolve these issues, here is the full code:
package mypackage;
import java.io.*;
public class Createwriteaddopenread {
public static void main(String[] args) {
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
try {
folderforallofmyjavafiles.mkdir(); //Creates a directory (mkdirs makes a directory)
if (folderforallofmyjavafiles.isDirectory() == true) {
System.out.println("Folder created at " + "'" + folderforallofmyjavafiles.getPath() + "'");
}
} catch (Exception e) {
System.out.println("Not working...?");
}
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
//I even tried this:
//File myfile = new File("folderforallofmyjavafiles/test.txt");
//write your name and age through the file
try {
PrintWriter output = new PrintWriter(myfile); //Going to write to myfile
//This may throw an exception, so I always need a try catch when writing to a file
output.println("myname");
output.println("myage");
output.close();
System.out.println("File created");
} catch (IOException e) {
System.out.printf("ERROR: %s\n", e); //e is the IOException
}
}
}
Thank you so much for helping me out, I really appreciate it.
:)
You're creating the Desktop folder in the C:\Users\username folder. If you check the return value of mkdir, you'd notice it's false because the folder already exists.
How would the system know that you want a folder named folderforallofmyjavafiles unless you tell it so?
So, you didn't create the folder, and then you try to create a file in the (nonexistent) folder, and Java tells you the folder doesn't exist.
Agreed that it's a bit obscure, using a FileNotFoundException, but the text does say "The system cannot find the path specified".
Update
You're probably confused about the variable name, so let me say this. The following are all the same:
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
folderforallofmyjavafiles.mkdir();
File x = new File("C:\\Users\\username\\Desktop");
x.mkdir();
File folderToCreate = new File("C:\\Users\\username\\Desktop");
folderToCreate.mkdir();
File gobbledygook = new File("C:\\Users\\username\\Desktop");
gobbledygook.mkdir();
new File("C:\\Users\\username\\Desktop").mkdir();
Is it possible to write a program from an IDE (such as NetBeans or Eclipse) that can compile from the command line and run once the user enters two arguments just after the name of the java class program to run?
If so, can an absolute path be passed in as one of the arguments?
And if so, (if the source or destination file has a multi-word descriptor, like Big Sky File.txt), how can it be passed in as an argument?
I know this is a lot of questioning, but I have searched high and low and nothing seems to so much as scratch the surface on any of these topics.
#Code-Guru, #thkala, here's the code I am attempting (took a bit to format):
edit: #Code-Guru, I have added the offending line (not sure how I missed that).
next edit: # Code-Guru, here is the updated file contents from CopyFile.java, and the resulting error message:
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException, NullPointerException
{
int num;
FileInputStream fileIn;
FileOutputStream fileOut;
try
{
// open input file
try
{
fileIn = new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{
System.out.println("Input File Not Found.");
return;
}
// open output file
try
{
fileOut = new FileOutputStream(args[1]);
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening Output File.");
return;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Incorrect argument use:java CopyFile Source Destination");
return;
}
// Copy File
try
{
do
{
num = fileIn.read();
if(num != -1)
{
fileOut.write(num);
}
}
while(num != -1);
}
catch(IOException e)
{
System.out.println("File Error: Could not copy file.");
}
fileIn.close();
fileOut.close();
}
}
Here is the error message I receive from the command prompt:
Error: Could not find or load main class CopyFile
Is it possible to write a program from an IDE (such as NetBeans or Eclipse) that can compile from the command line and run once the user enters two arguments just after the name of the java class program to run?
Yes, it is possible.
If so, can an absolute path be passed in as one of the arguments?
Definitely - any string can be passed as an argument, as long as its size does not exceed a certain (usually system-defined) limit.
And if so, (if the source or destination file has a multi-word descriptor, like Big Sky File.txt), how can it be passed in as an argument?
Typically, arguments with spaces, special characters e.t.c. are handled by the calling shell, rather than the Java program. Consult your documentation on how to properly quote such arguments in whatever command line shell you are using.
The answer lies in this part of the error message:
(wrong name: copyfile/CopyFile)
I.e., your class's fully qualified name is copyfile.CopyFile. Java requires that the package layout match the folder layout on disk so it knows how to find things.
So either your class file must be in a subfolder called copyfile, and then invoked as java copyfile.CopyFile, or you can compile your class in the unnamed default package by removing the package copyfile; declaration from the code (you haven't shown that line, but it must be there).
More info: http://www.jarticles.com/package/package_eng.html
Ive read a few threads here that relate the same problem, but the solutions arent working. :/
I use Eclipse, here is my program.
package mypackage;
import java.io.*;
public class myclass {
public static void main(String[] args) {
//String myfile = "/home/jason/workspace/myproject/src/mypackage/myscript.abc";
String myfile = "src/mypackage/myscript.abc";
File file1 = new File(myfile);
if(file1.exists()) {
log(myfile + " exists. length : " + myfile.length());
}
else{
log(myfile + " does not exist");
//System.exit(1);
}
//FileReader fr = new FileReader("myscript.abc");//I uncomment this and die inside
System.out.println("\nAbsPath : " + new File(".").getAbsolutePath());
System.out.println("\nuser.dir : " + System.getProperty("user.dir"));
}
public static void log(String s){
System.out.println(s);
}
}
The error I get, no matter what I try, or where I put myscript.abc (its peppered throughout the projects directory now) is this :
Unhandled exception type
FileNotFoundException myclass.java /myproject/src/mypackage
Wits end, pulling hairs.
Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage
This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
public static void main(String[] args) throws FileNotFoundException {
FileNotFoundException is a "checked exception" (google this) which means that the code has to state what the JVM should do if it is encountered. In code, a try-catch block or a throws declaration indicate to the JVM how to handle the exception.
For future reference, please note that the red squiggly underline in Eclipse means there is a compiler error. If you hover the mouse over the problem, Eclipse will usually suggest some very good solutions. In this case, one suggestion would be to "add a throws clause to main".
Use the file descriptor that you created and verified before creating the file reader. Also, you will probably run into problems using relative paths. Why is the line with the full path commented out? In any case, here is the code:
if(file1.exists()) {
log(myfile + " exists. length : " + myfile.length());
FileReader fr = new FileReader(file1);
}
I see that you tried to specify the full path to your file, but failed because of the following mistake:
you haven't declared or tried to catch java.io.FileNotFoundException.
To fix it, you can replace the line
FileReader fr = new FileReader("myscript.abc");
with the code:
try {
FileReader fr =
new FileReader("/home/jason/workspace/myproject/src/mypackage/myscript.abc");
} catch (FileNotFoundException ex) {
Logger.getLogger(myclass.class.getName()).log(Level.SEVERE, null, ex);
}
The following code is successfully compiled, and it should work:
package mypackage;
import java.io.*;
// It's better to use Camel style name for class name, for example: MyClass.
// In such a way it'll be easier to distinguish class name from variable name.
// This is common practice in Java.
public class myclass {
public static void main(String[] args) {
String myfile =
"/home/jason/workspace/myproject/src/mypackage/myscript.abc";
File file1 = new File(myfile);
if (file1.exists()) {
log("File " + myfile + " exists. length : " + myfile.length());
} else {
log("File " + myfile + " does not exist!");
}
try {
FileReader fr = new FileReader(myfile);
} catch (FileNotFoundException ex) {
// Do something with mistake or ignore
ex.printStackTrace();
}
log("\nAbsPath : " + new File(".").getAbsolutePath());
log("\nuser.dir : " + System.getProperty("user.dir"));
}
public static void log(String s) {
System.out.println(s);
}
}
This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
public static void main(String[] args) throws IOException{
}
You are expecting Eclipse to run the program in the project root directory. Unless you did something special with your "Run" configuration, I'd be suprised if it really starts there.
Try printing out your current working directory to make sure this is the right path.
Then try verifying that the bin / build directory contains your "*.abc" files, as they are not Java source files and may have not been copied into the compilation output directory.
Assuming that they are in the compliation directory, rewrite your file loader to use a relative path based on the class laoder's path. This will work well in exanded collections of .class files in directories (and later in packed JAR files).
Instead of trying to figure out what's going on, why not print what's going on...
Make this change to your code:
log(myfile.getName() + "(full path=" + myfile.getAbsolutePath() + ") does not exist");
You might find it either isn't using the directory you think, or (depending on your filesystem) it might be trying to create a file whose name is literally "src/mypackage/myscript.abc" - ie a filename with embedded slashes.
you can fix it simply declaring that throw this exception. Like this:
public static void main(String args[]) throws FileNotFoundException{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
}