FileNotFoundException java cannot basic find file while it's there - java

I'm trying to read a basic txt file that contains prices in euros. My program is supposed to loop through these prices and then create a new file with the other prices. Now, the problem is that java says it cannot find the first file.
It is in the exact same package like this:
Java already fails at the following code:
FileReader fr = new FileReader("prices_usd.txt");
Whole code :
import java.io.*;
public class DollarToEur {
public static void main(String[] arg) throws IOException, FileNotFoundException {
FileReader fr = new FileReader("prices_usd.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("prices_eur");
PrintWriter pw = new PrintWriter(fw);
String regel = br.readLine();
while(regel != null) {
String[] values = regel.split(" : ");
String beschrijving = values[0];
String prijsString = values[1];
double prijs = Double.parseDouble(prijsString);
double newPrijs = prijs * 0.913;
pw.println(beschrijving + " : " + newPrijs);
regel = br.readLine();
}
pw.close();
br.close();
}
}

Your file looks to be named "prices_usd" and your code is looking for "prices_usd.txt"

There are a couple of things you need to do:
Put the file directly under the project folder in Eclipse. When your execute your code in Eclipse, the project folder is considered to be the working directory. So you need to put the file there so that Java can find it.
Rename the file correctly with the .txt extn. From your screen print it looks like the file does not have an extension or may be it's just not visible.
Hope this helps!

It is bad practice to put resource files (like prices_usd.txt) in a package. Please put it under the resources/ directory. If you put it directly in the resources/ directory, you can access the file like this:
new FileReader(new File(this.getClass().getClassLoader().getResource("prices_usd.txt").getFile()));
But if you really have a good reason to put it in the package, you can access it like this:
new FileReader("src/main/java/week5/practicum13/prices_usd.txt");
But this will not work when you export your project (for example: as a jar).
EDIT 0: Also of course, your file's name needs to be "prices_usd.txt" and not just "prices_usd".
EDIT 1: The first (recommended) solution does return a string on .getFile() which can not directly be passed to the new File(...) constructor when the application is built / not run in the IDE. Spring has a solution to it though: org.springframework.core.io.ClassPathResource.
Simply use this code with Spring:
new FileReader(new ClassPathResource("prices_usd.txt").getFile());

Related

How to create a new text file based on the user input in Java?

I'm trying to create a new text file in java by having the user input their desired file name. However, when I look in the directory for the file after I run the code once, it doesn't show up.
import java.util.Scanner;
import java.io.File;
public class TestFile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
}
}
Although, when I don't have the user input a file name and just have the code written with the name in quotation marks, the file ends up being created when I look back in the directory.
File file = new File("TestFile.txt")
Why won't it create a file when I try to use the String input from the user?
You must be mistaken because just calling new File(String) won't create a file. It will just create an instance of File class.
You need to call file.createNewFile().
Adding this at the end creates the file:-
if (file.createNewFile()) {
System.out.println("File created.");
} else {
System.out.println("File already exists.");
}
The following code worked for me:
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
boolean isFileCreated = file.createNewFile(); // New change
System.out.print("Was the file created? -- ");
System.out.println(isFileCreated);
The only change made to your code is to call createNewFile method. This worked fine in all cases. Hope this helps.
From the API:
Atomically creates a new, empty file named by this abstract pathname
if and only if a file with this name does not yet exist. The check for
the existence of the file and the creation of the file if it does not
exist are a single operation that is atomic with respect to all other
filesystem activities that might affect the file. Note: this method
should not be used for file-locking, as the resulting protocol cannot
be made to work reliably. The FileLock facility should be used
instead.
Please use below code to solve your issue. You just have to call createNewFile() method it will create file in your project location. You can also provide the location where you want to create file otherwise it will create file at your project location to create file at specified location you have to provide location of your system like below
String fileLocation="fileLocation"+fileName;
File file = new File(fileLocation);
import java.util.Scanner;
import java.io.File;
public class TestFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
file.createNewFile();
}
}
When faced with issues like this, it's really, really, really important to go hit the JavaDocs, because 90% of the time, it's just a misunderstanding of how the APIs work.
File is described as:
An abstract representation of file and directory pathnames.
This means that creating an instance of File does not create a file nor does the file have to exist, it's just away of describing a virtual concept of a file.
Further reading of the docs would have lead you to File#createNewFile which is described as doing:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
When you initialize your File file = new File("TestFile.txt"), it is not created yet.
You should write something to your file using FileWriter or others.
File f = new File(fileName);
FileWriter w = new FileWriter(f);
w.write("aaa");
w.flush();
or using f.createNewFile() as suggested in other answer.
Then you can see your file and its content.

How can i write to a file when distributable file is launched?

I have program that read from a file. Now I created another task, that aims to update/write this file into same files. My problem now is when I generate my project's distributable file, during running and try to update my file, it does not write/update my changes. If I run it directly on my IDE, it works fine. This is wha I did so far:
private void tbleAddressMouseClicked(java.awt.event.MouseEvent evt) {
if(tbleAddress.getSelectedColumn()==3){
AddressUtil util = new AddressUtil();
List<AddressUtil> lists = util.getAddresses();
Address address = lists.get(tbleAddress.getSelectedRow());
if(tbleAddress.getValueAt(tbleAddress.getSelectedRow(), 0)!=null){
address.setRegion("\""+tbleAddress.getValueAt(tbleAddress.getSelectedRow(), 0).toString()+"\"");
}
lists.set(tbleAddress.getSelectedRow(), address);
try {
FileWriter fw;
fw = new FileWriter("./src/address.csv"); // This is where I doubt, if my **jar** file reads this directory
for(Address a:lists){
fw.append(a.getRegion);
fw.append(",");
fw.append(a.getAddressName());
fw.append("\n");
fw.flush();
}
fw.close();
} ...
My getAddresses is defined as:
public List<Address> getAddresses() {
List<Address> addresses = new ArrayList<>();
BufferedReader br = null;
InputStream in = this.getClass().getResourceAsStream("/address.csv");
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine())!=null){
String[] result = line.split(",");
Address address = new Address();
address.setRegion(result[0]);
address.setAddressName(result[1]);
addresses.add(address);
}...
My address.csv is of form:
"Region I","Sample St., Sample Address"
"Region II","Sample St., Sample Address 2"
...
Any help is much appreciated
Your issue with writing to the file is most likely due to the relative path you're using when you define the FileWriter. The dot in your path means "current working directory" so if your program is located at path C:\myProgram and you run your program such that it uses this path as the working directory then it's going to look for C:\myProgram\src\address.csv
So depending on the requirements for your program a relative path might be appropriate, in which case you need to determine what the correct path will be and ensure the file exists at that location, or you may to use some other mechanism to find the file.
I also notice that you're using getResourceAsStream to get an InputStream to your file. You should know that this only works if the file is available on the classpath of your program.

how to locate a file?

Hi I want to know how the program can locate a file.
For example. I have a class
public class MiReader {
private File file;
private BufferedReader bufferedReader;
public MiReader(String dir) {
try {
file= new File(dir);
bufferedReader = new BufferedReader(new FileReader(file));
} catch (Exception ex) {
Logger.getLogger(MiReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void imprimir() {
***
}
}
I know that the file is on the project (I'm using netbeans)
project is on C:\NetBeansProjects\Application
file: C:\NetBeansProjects\Application\file.txt
so when I instance MiReader must be something like this:
MiReader mr = new MiReader("C:\\NetBeansProjects\\Application\\file.txt");
and now if I run the program from another location
for example now its on
D:\Pograms\Application
so the file is D:\Pograms\Application\file.txt
and now I have to change the way I create the class to
MiReader mr = new MiReader("D:\\Pograms\\Application\\file.txt");
I want to know how the program can locate the file just running the program,
something like
MiReader mr = new MiReader(program.getLocation()+"\\file.txt")
Learning english :)
You could use relative paths. Aka
MiReader Mr = new MiReader("file.text");
This way the program will look for the file file.text inside the directory you run it from.
You can use System.getProperty to get the user.home, the user.dir, the classpath etc as a standard prefix for the file you are trying to open. Here are all of the System properties
ie
File f = new File (System.getProperty("user.home" + "/foo.txt"));

java FileInputStream cannot find file

I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`

Text input and output java

I am trying to read 2 files after i read the files i want to get their contents and manipulate the contents of the two files then update a new file which is the output. The files are in the same folder as the program but the program always throws a FileNotFoundException.
Below is my code:-
import java.io.*;
import java.util.Scanner;
public class UpdateMaster {
public static void main(String[] args)
{
String master = "Customer.dat";
String trans = "Transactns.dat";
String newMaster = "Temp.txt";
Scanner inputStreamMaster = null;
Scanner inputStreamTrans = null;
PrintWriter inputStreamNewMaster = null;
try
{
inputStreamMaster = new Scanner(new File(master));
inputStreamTrans = new Scanner(new File(trans));
inputStreamNewMaster = new PrintWriter(newMaster);
}
catch(FileNotFoundException e)
{
System.out.println("Error: you opend a file that does not exist.");
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error.");
System.exit(0);
}
do
{
String transLine = inputStreamTrans.nextLine();
String masterLine = inputStreamMaster.nextLine();
String[] transLineArr = transLine.split(",");
String[] masterLineArr = masterLine.split(",");
int trAccNo = Integer.parseInt(transLineArr[0]);
int sales = Integer.parseInt(transLineArr[1]);
int masterAccNo = Integer.parseInt(masterLineArr[0]);
int balance = Integer.parseInt(masterLineArr[1]);
while(masterAccNo== trAccNo){
inputStreamNewMaster.println(trAccNo+ " , "+masterAccNo);
masterLine = inputStreamMaster.nextLine();
masterLineArr = masterLine.split(",");
masterAccNo = Integer.parseInt(masterLineArr[0]);
balance = Integer.parseInt(masterLineArr[1]);
}
balance = balance + sales;
inputStreamNewMaster.println(masterAccNo+ " , "+balance);
}while(inputStreamTrans.hasNextLine());
inputStreamMaster.close();
inputStreamTrans.close();
inputStreamNewMaster.close();
//System.out.println(" the line were written to "+ newMaster);
}
}
Like #Ankit Rustagi said in the comments, you need the full path of the files if you want to keep the current implementation.
However, there is a solution where you only need the file names: use BufferedReader / BufferedWriter. See here an example on how to use these classes (in the example it uses the full path but it works without it too).
Use absolute path
String master = "C:/Data/Customer.dat";
String trans = "C:/Data/Transactns.dat";
String newMaster = "C:/Data/Temp.txt";
The code works for me, i guess you misspelled some filename(s) or your files are in the wrong folder. I created your files on the same level as the src or the project. Also this is the folder where the files are exspected.
There's nothing wrong with using relative paths like tihis. What's happening is that your program is looking for the files in the directory where you execute the program, which doesn't have to be the folder of the program. You can confirm this by logging the absolute path of the files before you try to read them. For example:
File masterFile = new File(master);
System.out.printf("Using master file '%s'%n", masterFile.getAbsolutePath());
inputStreamMaster = new Scanner(masterFile);
In general you should not hardcode file paths but allow the user to specify them in someway, for example using command line arguments, a configuration file with a well known path, or an interactive user interface.
There is a way to locate the program's class file but it's a little tricky because Java allows classes to be loaded from compressed archives that may be located in remote systems. It's better to solve this problem in some other manner.
Try this:
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("I look for files in:"+current);
To see what directory your program expects to find its input files. If it shows the correct directory, check spelling of filenames. Otherwise, you have a clue as to what's gone wrong.

Categories

Resources