File not found java - java

I have a problem when reading a text file in java. The class is FlashCardReader and I have the following constructor that handles the part of the reading.
public FlashCardReader( String fileName ) {
try{
reader = new BufferedReader(new FileReader(fileName));
}catch(FileNotFoundException e){
System.out.println("The file was not found or the name may be wrong!");
}
}
My main method looks like this:
public static void main(String[] args) {
FlashCardReader fcr = new FlashCardReader("Questions.txt");
}
And the final output is: The file was not found or the name may be wrong!
Some help would be greatly appreciated, cheers!

You can print the current directory of your java program where it is executed from with this java code,
System.out.println("CurrentDir: " + (new File(".").getCanonicalPath()));
Say it prints,
CurrentDir: D:\pkr\test
Then you can correctly choose a path through which your file can be correctly located.
Most likely, your src folder should be in test directory and in that case you can either move your file from src folder to test folder or refer your file in your code like this,
..\\Questions.txt
which should be able to read your file.
Let me know if this works.

Related

How to get File name from cmd argument to create a copy?

I'm working on a program that reads from a file with a custom extension I made. The idea is that an error report is created every time a file is read. The error report must be in whatever folder the source file was called from. The error file is a copy of the source file, but it has a line number at the beginning of each line and indicates at the end of the line if an error occurred at that line.
(I'm not trying to set up the numbering on this question, this question is just about creating the copy)
So for example, when I call my program from the command prompt:
C:\MyLocation>java =jar myJavaProgram.jar myFileToRead.CustomExtension
Asides from reading the file, it should also create a copy at the same location called myFileToRead-ErrorReport.txt
Additionally: If the source file has no extension, I have to assume that it's still the correct extension, so there won't always be a '.myCustomExtension' segment to replace into .txt
The problem is that I don't know how to grab the file name, because it's coming from the args list of the main method. I am using the following to read the file
public static void main(String[] args) throws FileNotFoundException {
try{
File inputFile = new File(args[0]);
Scanner sc = new Scanner(inputFile);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.out.println("File not found.");
}
}
So how can I get that file name to make something like
File errorReport = new File("./" + inputFileName + ".txt"); ?
First the code. The explanations appear after the code.
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("ERROR: Missing filename argument.");
}
else {
String filename = args[0];
if (filename.length() == 0) {
System.out.println("ERROR: Empty filename argument.");
}
else {
if (!filename.endsWith(".CustomExtension")) {
filename += ".CustomExtension";
}
String name = filename.substring(0, filename.indexOf(".CustomExtension"));
name += "-ErrorReport.txt";
File inputFile = new File(filename);
File directory = inputFile.getParentFile();
File errorReport = new File(directory, name);
System.out.println(errorReport.getAbsolutePath());
}
}
}
I make it a habit of checking the parameters. Hence I first check that the file name was supplied. If it was, then I check that it is not an empty string. Note that I have omitted some checks, for example checking whether the named file exists and is readable.
You wrote in your question that the file name argument may or may not include the .CustomExtension. Hence I check whether the supplied name ends with the required extension and append it if necessary. Now, since I know what the file name ends with, that means that the required part of the name is everything up to the extension and that's what the call to substring() gives me.
Once I have the required name, I just append the part that you want to append, i.e. -ErrorReport.txt.
Method getParentFile() in class java.io.File returns the directory that the file is located in. Hence I have the directory that the input file is in. Finally I can create the error report file in the same directory as the input file and with the desired file name. For that I use the constructor of class java.io.File that takes two parameters. Read the javadoc for details.
Note that creating a File object does not create the file. Creating an object to write to the file does, for example FileWriter or OutputStreamWriter.
Here is the code example to create a file, with filename passed from cmd line as argument and to get the same file name :
Class Demo{
public static void main(String[]args){
String path ="<path of file>"
String name= args[0];
File f = new File(path+name+".txt");
f.createNewFile(); //create file
System.out.println(f.getName()); // will give you the file name
}
}
cmd line : java -cp . Demo.java <filename>
Note : '.' used in the cmd if your class file is present in current dir
You can refer the code and modify to suit your requirement.
Hope this is what you are looking for.

No such file or directory found even though the file is in the same package

I am trying to scan the "loremIpsum.txt" file to a String using the split method of the class String to store each word in a different position of an array, and last use a HashSet to find if there is any word repetition in the text.
But Eclipse doesn't recognize the file even though it is in the same package. I was wondering if there is something wrong with my code?
package Lab5;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Lorem {
public static void main(String[] args) {
String[] loremIpsum = null;
try {
loremIpsum = new Scanner(new File("loremIpsum.txt")).next().split(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(loremIpsum.length);
HashSet h = new HashSet();
for(int i=0;i<loremIpsum.length;i++) {
String word=loremIpsum[i];
System.out.println(word);
if(h.contains(word)) {
System.out.println("we found a duplicate");
} else {
h.add(word);
}
}
}
}
Error message and proof "lorem.txt" is in the same package:
The file will be looked for in the project directory (where bin and src folders are located). Move the file there.
You need to pass the parameter as a path.
try this
String path = new File("").getAbsolutePath();
path.concat("/loremIpsum.txt");
loremIpsum = new Scanner(new File(path)).next().split(" ");
basically youre just finding the current path and appending the file name youre wanting to read from.
Like the others said though, you can move it to your working directory as well.
Cheers!
When you call the File constructor with a relative path, it's relative to the working directory.
That usually won't be the same directory as the code calling the constructor. But that's okay, because if your file can be specified when you run the application, you don't want to presume that anyway.
You can specify the working directory in the Eclipse run configuration, on the Arguments tab.
You can see how a relative path has been resolved using the File method getAbsolutePath().
try {
File myFile = new File("loremIpsum.txt");
System.out.println("Absolute path = " + myFile.getAbsolutePath() );
loremIpsum = new Scanner(myFile).next().split(" ");
...

Directory not showing up in desktop, and file not being created?

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();

My java code is flawed, but i dont understand why

I am very new at java and my be missing something very basic. When i run my code i am trying to add value to accounts created in the code. When i try to run the code i recieve an error that a file cannot be found, but i thought that the file was created inside the code.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class DoPayroll
{
public static void main(String args[])
throws
IOException
{
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
for (int empNum = 1; empNum <= 3; empNum++)
{
payOneEmployee(diskScanner);
}
}
static void payOneEmployee(Scanner aScanner)
{
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
aScanner.nextLine();
}
}
once run i recieve the following error
Exception in thread "main" java.io.FileNotFoundException: EmployeeInfo.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at DoPayroll.main(jobexe.java:11)
i thought that in the above code using new Scanner(new File("EmployeeInfo.txt") would create the new file once i input a value. Please give me a simple solution and an explanation.
It will create a new file when you write to it. However to read from it, it must already exist. You might like to check it exists with
File file = new File("EmployeeInfo.txt");
if (file.exists()) {
Scanner diskScanner = new Scanner(file);
for (int empNum = 1; empNum <= 3; empNum++)
payOneEmployee(diskScanner);
}
The File object can't find the filename you've passed. You either need to pass the full path of EmployeeInfo.txt to new File(...) or make sure current working directory is the directory that contains this file.
The File constructor does not create a file. Rather, it creates the information in Java needed to access a file on disk. You'd have to actually do file IO in Java using the created File for a new file to be created.
The Scanner constructor requires an existing File. So you need a full path to the real, valid location of EmployeeInfo.txt or to create that file using File I/O first. This tutorial on I/O in Java will help.
You are mistaking instantiating an instance of class File with actually writing a temp file to Disk. Take this line
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
And replace it with this
File newFile = File.createTempFile("EmployeeInfo", ".txt");
Scanner diskScanner = new Scanner(newFile);
Edit: Peter makes a good point. I'm face palming right now.
You thought wrong :D A Scanner needs a existing file, which seems quite logical as it reads values and without a existing file its difficult to read. The documentation also states that:
Throws:
FileNotFoundException - if source is not found
So, in short: You must provide a readable, existing file to a scanner.
As the other answer explain, the file is not created just by using new File("EmployeeInfo.txt").
You can check is the file exists using
File file = new File("EmployeeInfo.txt");
if(file.exists()) {
//it exists
}
or you can create the file (if it doesn't exists yet) using
file.createNewFile();
that method returns true if the file was created and false if it already existed.

Java, reading a file from current directory?

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me

Categories