File Not Found Exception? - java

I'm trying to read in a file, and throw each word into an arraylist, but it keeps saying it can't find the file. I've double checked (and triple, and quadruple, lol) that the file names match with correct extension and in the same directory. I feel like I'm missing something obvious. Also, I know there are other ways to read a file, but we haven't learned those yet in my class so I want to get this to work using the Scanner class.
public class FrequencyAnalysis {
private static ArrayList<String> words = new ArrayList<>();
public static void read() throws IOException {
String token;
Scanner inFile = new Scanner(new File("plaintext.txt"));
while (inFile.hasNext()){
token = inFile.next();
words.add(token);
}
}
}
public class FrequencyAnalysisTester {
public static void main(String[] Args) throws IOException {
FrequencyAnalysis.read();
}
}

The current directory may differ from the directory of .class file.
If your file is in the class path ,this code solve your problem
URL path = ClassLoader.getSystemResource("myFile.txt");
File f = new File(path.toURI());
Refer this answer for more details
Java, reading a file from current directory?

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.

Unable to read from a text file

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.

Java Regex Expression isn't working for File Validation

I'm trying to validate a filepath a user has entered through a swing box. They click on the location where they want the file and then they add the name of the file by themselves. So they need to make sure it is in the format such as "C:/files/documents/hello.txt and they need to specify the file type at the end so i can create a new file to write to. The isFile method doesn't seem to satisfy this as the file has to exist, so i'm trying to use regex now with an if statement to validate the file path .
public class Main {
public static void main (String [] args) throws FileNotFoundException {
String fileName = "C:/users/furquan/hello.txt";
File zerina = new File (fileName);
//FileInputStream fis = new FileInputStream (zerina);
String regex = "\\^(?:[\w]\:|\\\)(\\\[a-z_\-\s0-9\.]+)+\\\.(txt|gif|pdf|doc|docx|xls|xlsx)$";
System.out.println (fileName.matches(regex));
}
}
I know you need to add more slashes in java regex because of the escape sequence but i can't get it to work
Use java.nio.file.Path. (you don't need Regexs)
for example :
// imports
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("C:/users/furquan/hello.txt");
Path parent = path.getParent();
if (Files.exists(parent) && path.getFileName().endsWith(".txt")) {
// your code goes here
}
EDIT :
Also, if you want to validate file names :
static final Pattern FILE_NAME_PATTERN = Pattern.compile("([\\w\\d\\s\\-\\.])+\\.(txt|gif|pdf|doc|docx|xls|xlsx)");
public static void main(String[] args) throws Exception {
String s = "C:/users/furquan/hello.txt";
System.out.println(createFile(s));
}
static boolean createFile(String fileName) throws IOException {
Path path = Paths.get(fileName);
if (Files.exists(path)) {
return true;
}
if (FILE_NAME_PATTERN.matcher(path.getFileName().toString()).matches()) {
Path parent = path.getParent();
if (!Files.exists(parent)) {
Files.createDirectories(parent);
}
Files.createFile(path);
return true;
}
return false;
}
You have way too much escaping and unnecessary stuff in your regex. None of the characters you're dealing with need escaping, and in fact escaping them breaks your regex.
Try this:
String regex = "(?i)[A-Z]:[\\\\\\w\\s.-]+)\\.(txt|gif|pdf|docx|doc|xlsx|xls)";
Since matches() must match the whole string, ^ and $ are implied, so leave them out.

FileNotFoundException. i dont understand

i can seem to understand why my code isn't compiling. Everytime I run it, I get a FILENOTFOUNDException. Any help would be much appreciated. :D
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();
}
Basically the exception message means the filename you specified is not an existing file in executions directory.
EDIT[copied from my comment]
That file should be located where compilation is done, if you are using eclipse or intellij it should be at your projects root directory.
+ Because you are passing in a relative path and not an absolute one to the file, java is recognizing it as a relative to execution directory which is located where followin code points to.
To check what is that desired input files directory simply use
getAbsolutePath() on that file.
For instance:
File input = new File("EmployeeInfo.txt");
System.out.println("Move .txt to dir:" + input.getAbsolutePath());
Scanner diskScanner = new Scanner(input);
Then move the source .txt file to that location

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"));
}
}

Categories

Resources