Unable to read from a text file - java

I am trying to read from a text file. I have the file created, it only needs to have one record, but it could have more. I keep getting errors. I am a Geography student, not an IT guy, I am hoping to figure out the next step once I get this. Here is my example, that doesn't work:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Driver
{
public static void main(String[] args) throws IOException
{
File data;
String fileName = null; // User input file name
Scanner input;
input = new Scanner(System.in);
System.out.println("Enter file name (ie: text.txt): ");
data = new File(input.next());
Scanner read;
read = new Scanner(data);
fileName = read.nextLine();
System.out.println(fileName);
}
}

I believe an error that you are having is not referencing the correct place when trying to access the file. If you just type in example.txt, the java compiler has no idea where to find this file.
Try this:
Right click under the package
Create new folder, and call it 'texts'
Open file explorer
Paste all your .txt files into this new folder 'texts'
Replace fileName = read.nextLine(); with fileName = "texts/" + read.nextLine();
After this you should be good to go!

You have two options.
Put text.txt file in same folder where your class files are.
Get full path of the file from user like C:\text.txt.
It'll run.

Related

Need assistance with Java IntelliJ not reading my file

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.

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.

FileNotFoundException java cannot basic find file while it's there

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

Inputting a text file into a program?

I had a lecture today on inputting and outputting but it didn't really seem to explain where the text file is etc..
here is my code:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I get a file not found exception but the text file is in the same folder as the program?
Please first read up on the difference between relative and absolute paths. An absolute path is:
C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\lab1task3.txt
A relative path would be just "lab1task3.txt", which is what is given. That means that lab1task3.txt can be found relative to the working directory (e.g if the working directory was "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" then it would find it).
However, you could also use an absolute path, but remember that doing so means that it will only work if a file is in the same place on the machine running it. E.g, if you submit with "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" in your code then it will only work if someone else has that same file and location on their computer. Please note that if this is an assignment, the module convenor/marker probably does not have afolder called C:\Users\Ceri.... If you submit your work using a relative path, anyone using your code just needs to make sure the file is relatively in the same place (e.g in the same folder).
If this doesn't matter, you need to escape the back slash characters with another back slash in the path. This should work:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I notice you are using eclipse. Your "working directory" is your workspace. Therefore you want to move your file to:
C:\Users\Ceri\workspace1\inputoutput\lab1task3.txt
This should work for you using a "relative" path which you had in your opening post.
You're confusing class file location and the "user's working directory", the latter being what Java uses to determine the root of the file path (unless absolute paths are needed), and you can find its location easily via:
System.out.println(System.getProperty("user.dir"));
I advise you to forgo use of files altogether when all you need to do is read in data, and instead get the text file as a program resource:
// where you swap the name of your class for MyClass
InputStream fileResource = MyClass.class.getResourceAsStream("myFile.txt");
Scanner scanner = new Scanner(inputStream);
Note that if you must use a File, then find out what the user's working directory is, as shown above, and then tailor your file path so that it is relative to this working directory.
Try:
File file = new File("src/inputoutput/lab1task3.txt");
My guess is that your current working directory is not the same place as the project location. If your working directory were, the file would definitely be found if it does indeed have that name.
To workaround this issue you can always be using a InputStream instead, like so:
InputStream inputStream = new InputStream("lab1task3.txt");
Scanner scanner = new Scanner(inputStream);
If you want to see your current working directory you can use something like this:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}

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