Need assistance with Java IntelliJ not reading my file - java

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.

Related

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.

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

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.

How to get the list of files under the directory in a JAR file

I want to know the list of files under the 'META-INF/config' directory in a JAR file.
I am using the below code to retrieve the files list. But it is failing.
Enumeration<URL> path = Thread.currentThread().getContextClassLoader().getResources("META-INF/config/");
while(path.hasMoreElements())
{
URL path1 = path.nextElement();
System.out.println("File =" +path1.getFile());
File configFolder = new File(path1.getPath());
File[] files = configFolder.listFiles();
for (File file : files)
{
System.out.println("\nFile Name =" + file.getName());
}
}
Can somebody help me in fixing this?
Thanks In Advance,
Maviswa
try below code
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
import java.io.*;
public class JarContents{
public static void main(String[] args) throws IOException{
JarContents mc = new JarContents();
}
public JarContents() throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter jar file name: ");
String filename = in.readLine();
File file = new File(filename);
if(!filename.endsWith(".jar")){
System.out.println("Invalid file name!");
System.exit(0);
}
else if(!file.exists()){
System.out.println("File not exist!");
System.exit(0);
}
try{
JarFile jarfile = new JarFile(filename);
Enumeration em = jarfile.entries();
for (Enumeration em1 = jarfile.entries(); em1.hasMoreElements();) {
System.out.println(em1.nextElement());
}
}
catch(ZipException ze){
System.out.println(ze.getMessage());
System.exit(0);
}
}
}
Good Luck!!!
I remember having to do this a while back to read in a jar's manifest.mf to extract its version information to display. Given that all properly built jars have manifests, trying to access them as a resource is impossible (they all have the same path), and as such, had to examine the jar individually as a zip file.
Given that you aren't providing information as to where the failure is, it is difficult to guess as to what your problem is. I'm not sure if it is not finding the file that you are expecting, or if it is reading the wrong file, or if you are getting NPEs, etc.
try adding a "/" or "./" before the META-INF in the getResources() call
e.g.
...
read.currentThread().getContextClassLoader().getResources("./META-INF/config/");

Categories

Resources