FileInputStream error Java - java

I am trying to read a file in Java called "KFormLList.txt". It is saved in the default package along with this program, yet when I try to run it I get this error message: "Error: KFormLList.txt (The system cannot find the file specified)"
What am I doing wrong? Thanks for any help.
import java.io.*;
public class VLOCGenerater {
/**
* #param args
*/
public static void main(String[] args) {
try {
//Read the text file "KFormLList.txt"
FileInputStream fis = new FileInputStream("KFormLList.txt");
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String strLine;
int V = 0;
int LOC = 0;
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
System.out.println(strLine);
V++;
}
else {
LOC++;
}
}
System.out.println("V = " + V);
System.out.println("LOC = " + LOC);
dis.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}

Try putting the text file in the root directory of your project.
The name parameter passed into the FileInputStream constructor is the path name to the file in the file system.
A pathname, whether abstract or in string form, may be either absolute
or relative. An absolute pathname is complete in that no other
information is required in order to locate the file that it denotes. A
relative pathname, in contrast, must be interpreted in terms of
information taken from some other pathname. By default the classes in
the java.io package always resolve relative pathnames against the
current user directory. This directory is named by the system property
user.dir, and is typically the directory in which the Java virtual
machine was invoked.
I assumed you were using Eclipse, by default Eclipse sets the user.dir to your the root of your project. From reading other material, Netbeans follows the same convention.
This can be tested with the following code, which should output the path to your project:
System.out.println(System.getProperty("user.dir"));
Placing the file in the root of your directory allows it to be found by the FileInputStream.

If you're using NetBeans (perhaps similar for Eclipse), make sure that your file is in NetbeansProjects/YourProject/
If you have compiled your program to .jar file, put the txt to same place where .jar is.

Either you put the file in the "root directory" of your project or provide the "absolute path" of the file as argument to FileInputStream.
Hope that helps. :).

This way, the program expects the file in the working folder,. i.e. where you execute java. For loading from classpath (Default package), try getResourceAsStream.

Related

Specifying file path in java causes FileNotFoundException

This piece of code throws a FileNotFoundException, i'm sure the file exists in my working directory, am i doing something wrong?
private void generateInvoiceNumber(){ //uses reads previous invoice number and increments it.
try {
File invoiceFile = new File("./Invoices/invoiceFile.txt");
FileWriter writer = new FileWriter(invoiceFile,false);
Scanner getter = new Scanner(invoiceFile);
this.invoiceNumber = getter.nextInt();
writer.write(++invoiceNumber);
writer.close();
getter.nextInt();
getter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
My tip:
Print (in your code) the current path location.
Then you can use this path in order to find the exact path you should use in order to access your file.
Maybe you should put more concrete absolute path:
File invoiceFile = Paths.get ("C:","Invoices", "invoiceFile.txt").toFile();
or if you trying to get from current path:
File invoiceFile = Paths.get (".","Invoices", "invoiceFile.txt").toFile();
And you can check your . path:
System.out.println(new File(".").getCanonicalPath());
Which operating system you are using?
It’s better to use paths when you are constructing a path to your file like
File file = Paths.get (".","Invoices", "invoice.txt").toFile();
corrected " symbols and default root "." which is your folder where app started.

How to read from a text file in java when its not saved in the same place

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)

reading an external file using TextIO

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'.

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;
}`

Problem with relative file path

So here is my program, which works ok:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;
public class ScanSum {
public static void main(String[] args) throws IOException {
Scanner s = null;
double sum = 0;
try {
s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
s.useLocale(Locale.US);
while (s.hasNext()) {
if (s.hasNextDouble()) {
sum += s.nextDouble();
} else {
s.next();
}
}
} finally {
s.close();
}
System.out.println(sum);
}
}
As you can see, I am using absolute path to the file I am reading from:
s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
The problem arises when I try to use the relative path:
s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));
I get an error:
Exception in thread "main" java.lang.NullPointerException
at ScanSum.main(ScanSum.java:24)
The file usnumbers.txt is in the same directory as the ScanSum.class file:
D:/java-projects/HelloWorld/bin/ScanSum.class
D:/java-projects/HelloWorld/bin/usnumbers.txt
How could I solve this?
If aioobe#'s suggestion doesn't work for you, and you need to find out which directory the app is running from, try logging the following:
new File(".").getAbsolutePath()
From which directory is the class file executed? (That would be the current working directory and base directory for relative paths.)
If you simply launch the application from eclipse, the project directory will be the working directory, and you should in that case use "bin/usnumbers.txt".
The NullPointerException is due to the fact that new FileReader() expression is throwing a FileNotFoundException, and the variable s is never re-assigned a non-null value.
The file "usnumbers.txt" is not found because relative paths are resolved (as with all programs) relative to the current working directory, not one of the many entries on the classpath.
To fix the first problem, never assign a meaningless null value just to hush the compiler warnings about unassigned variables. Use a pattern like this:
FileReader r = new FileReader(path);
try {
Scanner s = new Scanner(new BufferedReader(r));
...
} finally {
r.close();
}
For the second problem, change directories to the directory that contains "usnumbers.txt" before launching java. Or, move that file to the directory from which java is run.
It must be a FileNotFoundException causing NPE in the finally block.
Eclipse, by default, executes the class with the project folder (D:/java-projects/HelloWorld in your case ) as the working directory. Put the usnumbers.txt file in that folder and try. Or change the working directory in Run Configuration -> Argument tab
Since your working directory is “D:/java-projects/HelloWorld”
#pdbartlett's id is great, But
String filePath = new File(".").getAbsolutePath()
will output "D:/java-projects/HelloWorld/." which is not easy to add your extra relative path like "filePath" + "/src/main/resources/" + FILENAME which located in resources folder.
I suggest with String filePath = new File("").getAbsolutePath() which return the project root folder
In Eclipse, you can also look under "Run Configurations->Than TAB "Classpath".
By default the absolut path is listed under "User Entries" in [icon] 'your.path' (default classpath)
Put the file in resources folder.
ClassLoader classLoader = getClass().getClassLoader();
String file1 = classLoader.getResource("myfile.csv").getPath();

Categories

Resources