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.
Related
I need some assistance with my Java project being unable to read my file that is in the same directory as my classes. Here is the snippet:
private static final String FILENAME = "my_address.txt";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
AddressBook book = new AddressBook();
book.readFile(FILENAME);
int choice;
do...
Whenever I try to bring in my text file (my_address.txt),I receive this message...
my_address.txt could not be found! Exiting..
Process finished with exit code 0
Can someone please assist me with getting my file onto my project?
In the same file directory
As someone has mentioned in the comments, here is a snippet of my AddressBook portion:
package Animal;
public class AddressBook {
private ArrayList<Person> people;
public AddressBook()
{
this.people = new ArrayList<>();
}
public void readFile(String filename)
{
Scanner fileReader;
try
{
fileReader = new Scanner(new File(filename));
while(fileReader.hasNextLine())
{
String[] data = fileReader.nextLine().trim().split(",");
String firstName = data[0];
String lastName = data[1];
String address = data[2];
String phone = data[3];
people.add(new Person(firstName, lastName, address, phone));
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println(filename + " could not be found! Exiting..");
System.exit(0);
}
}
From the image linked to in your question, it looks like you are using IntelliJ as your IDE. So when you build your java source code, file my_address.txt gets copied to the same directory that contains the compiled class which in your case appears to be Main. So file my_address.txt should be in the same directory as file Main.class
The following line of code creates a path to a file.
new File(filename)
If the value of variable filename is my_address.txt then the path to the directory containing file my_address.txt will be the working directory. If you don't know what the working directory is, the following [java] code will get it for you.
String pathToWorkingDirectory = System.getProperty("user.dir");
You will find that it is not the same directory that contains the file Main.class and that's why you are getting the FileNotFoundException.
In your case, file my_address.txt is referred to as a resource and the JDK includes an API for retrieving resources.
Hence in order to fix your code such that it does not throw FileNotFoundException, either use the API for retrieving resources or move file my_address.txt to the working directory.
If you use the API, then the following java code shows how to create a Scanner for reading the file. Note that I assume that class Main is in the same package as class AddressBook, which, according to the code in your question, is package Animal. By the way, it is recommended to adhere to java naming conventions so the name of the package should be animal.
java.net.URL url = Main.class.getResource("my_address.txt");
if (url != null) {
try {
java.net.URI uri = url.toURI(); // throws URISyntaxException
java.io.File f = new java.io.File(uri);
java.util.Scanner fileReader = new java.util.Scanner(f); // throws FileNotFoundException
}
catch (java.net.URISyntaxException | java.io.FileNotFoundException x) {
x.printStackTrace();
}
}
else {
// The file was not found.
}
The above code uses multi catch.
I also recommend printing the stack trace in the catch blocks in your code.
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());
Im trying to write a function that will take a string, then open a file with that string name and read the text. I know how to do this, but im having trouble with the fact that my text files are not saved in the same place as my java file.
It looks like this.
Project name/src/program.java
Project name/resources/text.txt
Im using the File class, but dont know what to put in the File constructor to open to the right place.
ie. File store = new File(xxxxxxxxxtext.txt)
Help me out with what goes in front of the file name please. Also, this is java 6 and im on windows 8.
This is my code:
public static void areaSearch(String a) {
Scanner reader = null;
try {
reader = new Scanner(new File("../resources/" + a+ ".txt"));
}
catch (Exception e) {
System.out.println("File: " + a +" not opended...");
}
Use relative path if it's on an easy relative path from your project folder:
File file = File("../resources/text.txt");
Or use absolute path:
File file = File("C:\\abcfolder\\text.txt");
Read documentation. There are more, than 1 constructor for File class. Use:
public File(File parent, String child)
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
This is my code to read a text file. When I run this code, the output keeps saying "File not found.", which is the message of FileNotFoundException. I'm not sure what is the problem in this code.
Apparently this is part of the java. For the whole java file, it requires the user to input something and will create a text file using the input as a name.
After that the user should enter the name of the text file created before again (assume the user enters correctly) and then the program should read the text file.
I have done other parts of my program correctly, but the problem is when i enter the name again, it just can not find the text file, eventhough they are in the same folder.
public static ArrayList<DogShop> readFile()
{
try
{ // The name of the file which we will read from
String filename = "a.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
ArrayList<DogShop> shops = new ArrayList<DogShop>();
// Read each line until end of file is reached
while (in.hasNextLine())
{
// Read an entire line, which contains all the details for 1 account
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
// 1st part is the account number
try
{ int shopNumber = lineBreaker.nextInt();
// 2nd part is the full name of the owner of the account
String owner = lineBreaker.next();
// 3rd part is the amount of money, but this includes the dollar sign
String equityWithDollarSign = lineBreaker.next();
int total = lineBreaker.nextInt();
// Get rid of the dollar sign;
// we use the subtring method from the String class (see the Java API),
// which returns a new string with the first 'n' characters chopped off,
// where 'n' is the parameter that you give it
String equityWithoutDollarSign = equityWithDollarSign.substring(1);
// Convert this balance into a double, we need this because the deposit method
// in the Account class needs a double, not a String
double equity = Double.parseDouble(equityWithoutDollarSign);
// Create an Account belonging to the owner we found in the file
DogShop s = new DogShop(owner);
// Put money into the account according to the amount of money we found in the file
s.getMoney(equity);
s.getDogs(total);
// Put the Account into the ArrayList
shops.add(s);
}
catch (InputMismatchException e)
{
System.out.println("File not found1.");
}
catch (NoSuchElementException e)
{
System.out.println("File not found2");
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
} // Make an ArrayList to store all the accounts we will make
// Return the ArrayList containing all the accounts we made
return shops;
}
If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)
If not, you should specify the absolute path to that file.
Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.
If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.
Well.. Apparently the file does not exist or cannot be found. Try using a full path. You're probably reading from the wrong directory when you don't specify the path, unless a.txt is in your current working directory.
I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath
If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.
This is according to Core Java Volume I, section 3.7.3.
If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use
Scanner in = new Scanner(Paths.get("myfile.txt"));
But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.
This should help you..:
import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
find(Recipe);
}
public void find(String Name){
String newRecipe= Name+".txt";
try{
FileReader fr= new FileReader(newRecipe);
BufferedReader br= new BufferedReader(fr);
String str;
while ((str=br.readLine()) != null){
out.println(str + "\n");
}
br.close();
}catch (IOException e){
out.println("File Not Found!");
}
}
}
Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.
NOTE: It also works when used with System.err.print("Error Message Here")