Java program file not found - java

I have looked through questions that have been posted here regarding this problem, and none of the solutions have been helpful. I found a link to this page http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.File%29
also, not helpful. I have looked through my text book, even copied a similar code straight from the book, and was again given the File Not Found Exception. The input.txt file is in the same folder as the program file, and I tried to use a specific path, also added this line to the code System.out.println(new File("C:/input.txt").getAbsolutePath());
it also did not help. I feel like I have more questions now than answers. The name of the file is correct, and case is correct. I did find that the .txt files are being saved in Word, so I went there and changed the format to plain txt file. Does it being saved as a Word document have something to do with this problem, or am I wasting time there?
Here is my code:
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class FileRead
{
public static void main(String[] args) throws IOException
{
double count = 0;
double sum = count++;
double average = sum/count;
File fileObject = new File("C:/input.txt");
System.out.println(new File("C:/input.txt").getAbsolutePath());
Scanner fileIn = new Scanner (fileObject);
while (fileIn.hasNext())
{
count = fileIn.nextDouble();
sum = count++;
}
average = sum/count;
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println("The total of the: " + count + "numbers entered are: "
+ sum + " and the average is: " + df.format(average));
}
}

C:/input.txt is telling the file system to look for a file called input.txt at the root of the hard drive, assuming C:/ is equivalent to C:\.
Is this where you are running the program in the root directory. If not, and there is no file called input.txt in the root director the program won't work as expected.
Try changing the the code as described by BlackCode, and/or removing the C:/
Typing pwd in a command window will tell you what directly you are in, and if its not the root of your hard drive the program can not find the file you are telling it too look for.

You need to escape the slash: "C://input.txt".

In file path change "/" to File.separator
Example:
File fileObject = new File("C:" + File.separator + "input.txt");

"The input.txt file is in the same folder as the program file": that means you only need "input.txt"
To see the files exactly with the names saved you can go to the command window and type dir at the location where you are looking for.
Alternately you can do that from within the program:
File f=new File(".");
String[] fs=f.list();
for(String s:fs) System.out.println(s);
If your file doesnt print then it's somewhere else.

Your code looks fine and it works fine on my Window 7 (although I had to change to administrator to create the c:\input.txt)
It is confusing that .getAbsolutePath() gives a value even if the file does not exist.
A better test is the following - it will print false if your file does not exist.
File fileObject = new File("c:/input.txt");
System.out.println(fileObject.exists());
Scanner fileIn = new Scanner (fileObject);
To be certain the file exists try this at the command line
echo 1 2 3 4 > input.txt
Then get rid of the full path and just use "input.txt" as the file name.

Use this :
Scanner fileIn = new Scanner ("C:/input.txt");

Related

File not found 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.

Resolving Path Differences Between Mac and Windows

I am new to Stack Overflow and fairly new to programming, so hopefully this makes sense. I am writing a java program that creates a file in a specific directory. My program works on Windows and creates a file in the right location, but it does not work on Mac. I have tried changing the backslashes to a single forward slash, but that doesn't work. How should I change the code so that it works for Mac or ideally for both? I've put some of the code below.
Thanks in advance!
Class that creates new path for file:
try{
//Create file path
String dirpath = new ReWriterRunner().getPath()+"NewFiles";
//Create directory if it doesn't exist
File path = new File(dirpath);
if (!path.exists()) {
path.mkdir();
}
//Create file if it doesn't exist
File readme = new File(dirpath+"\\README.md");
if (!readme.exists()) {
readme.createNewFile();
}
Method that gets user input on where to put file:
public static String getPath(){
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter the directory name under which the project files are stored.");
System.out.println("Example: C:\\Users\\user\\work\\jhipstertesting)");
System.out.println("Use double slashes when typing.");
s = in.nextLine();
return s;
}
you can use system properties to identify the system you are currently operating on ..
more info at https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
but i would prefer using NIO. but that is your choice
https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
Forward slash "/" must be used to get the file path here. for ex.> Use:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();

Program not reading txt file

I am a beginner Java student, working on our first class assignment.
In this assignment, I need to read a txt file, and fill an array with its contents, first space in the array per line.
My professor gave us code to do this, but I keep getting an error that the file cannot be read each time I try.
I am using Netbeans 8, on a Mac, and the file States.Fall2014.txt is located in the src folder, with all of my java classes.
Exception in thread "main" java.io.FileNotFoundException: States.Fall2014.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at main.main(main.java:21)
Java Result: 1
Here is the code I have. I have only included the code that pertains to opening the file, as I'm sure you have no wish to be spammed with the other classes.
The commented code during the trimming is to echo print, to make sure the file is being read in properly (not currently needed since the file isn't being read in at all).
import java.io.*;
public class main {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
StateCollection Sdriver = new StateCollection(50);
//Sdriver = new StateCollection(50);
//Creates object of collection class
FileReader fr= new FileReader("States.Fall2014.txt");
BufferedReader br1 = new BufferedReader (fr);
String inputString;
String stateName;
String stateCapital;
String stateAbbrev;
int statePop;
String stateRegion;
int stateRegionNum;
inputString = br1.readLine();
while (inputString != null)
{
stateName = inputString.substring(1, 15).trim();
//System.out.println("stateName read in was: " + stateName);
stateCapital = inputString.substring(16, 30).trim();
//System.out.println(“stateCapital read in was: “ + stateCapital);
stateAbbrev = inputString.substring(31, 32).trim();
//System.out.println(“stateAbbrev read in was: “ + stateAbbrev);
statePop = Integer.parseInt(inputString.substring(33, 40));
//System.out.println(“statePop read in was: “ + statePop);
stateRegion = inputString.substring(41, 55).trim();
//System.out.println(“stateRegion read in was: “ + stateRegion);
stateRegionNum = Integer.parseInt(inputString.substring(56));
//System.out.println(“stateRegionNum read in was: “ + stateRegionNum);
//Code to create object
inputString = br1.readLine(); // read next input line.
}
br1.close(); //Close input file being read
Change
FileReader fr= new FileReader("States.Fall2014.txt");
to
FileReader fr= new FileReader("src/States.Fall2014.txt");
or move the file up one level to the project directory.
Make sure that the TXT file is in the right folder/area.
You shouldn't have it with your class, as the other answer states, you need it in the root folder.
Move the file up one level, to the same as the src folder.
The src directory is not (necessarily) the directory the .class file is in. Make sure States.Fall2014.txt is on the class-path.

Pass multiple files to another class

How to pass multiple files to another class?
I am developing an application which first compresses the image and after that it'll convert it into pdf.
The program which i have written works well seperately ie; it compresses the image and then in another project i use the path where the image are stores to convert it to pdf.
Now i want to have both these codes in the same project and i am encountering the problem where i am creating a loop where i pass the path name one by one. The source path works well but i need to specify the destination path which changes the name dynamically this where i am facing the problem. I have attached the code below please tell me what to do.
System.out.println("before convert");
Conversion cc = new Conversion();
File directory = new File(Success);
File[] files = directory.listFiles();
if(files!=null)
{
for(File f:files){
String path = f.getName();
System.out.println("The Name of file is="+path);
cc.createPdf("path" , "output", true);
System.out.println("the file is ="+output+".pdf");
System.out.println("after convert");
}
}
In the above code i need to change the output file name dynamically here cc.createPdf("path" , "output", true);
A simple implementation would be to keep a counter outside loop and increment it before appending it to output file name
int counter = 0;
for(File f:files){
String path = f.getName();
System.out.println("The Name of file is="+path);
counter++; //increment the counter
cc.createPdf("path" , "output"+counter, true); // append it to output
System.out.println("the file is ="+output+".pdf");
System.out.println("after convert");
}
For more robustness, counter can be replaced by UUID generator, System time in milliseconds etc
Im guessing your having trouble getting a File object with a newly created .pdf extension, you will have to adapt this to your code but it should be pretty straight forward.
File inputFile = new File("c:\\myimage.png");
String fileName = inputFile.getName();
File pdfFile = new File(inputFile.getParent(), fileName.substring(0, fileName.indexOf(".")) +".pdf");
System.out.println(inputFile + " " + pdfFile);
I think you should keep things simple by just appending ".pdf" to the names. The fact that you are processing a directory ensures that the source file names are unique. Hence, the new ".pdf" names would also be unique.
Assuming your output files land in the same directory, it also becomes much easier to sort files by names and know immediately which ".pdf" files correlate to which source files.
So, your output file name simply becomes
String path = f.getName();
String output = path.substring(0, path.lastIndexOf('.')) + ".pdf";

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.

Categories