I have the following code for reading a excel sheet in Java using the Apache POI. Although the file exists, why does it give me a FileNotFound Exception?
import org.apache.poi.hssf.usermodel.HSSFSheet;
import java.io.FileInputStream;
import java.io.File;
public class ReadFromExcel {
public static void main(String[] args) {
FileInputStream file = new FileInputStream(new File("C:\\Personal\\test.xlsx"));
}
}
I just copied and pasted the File location from windows explorer so I know that the file exists for sure. Then Why can't Java find it?
Used same path with the "File" class instead of "FileInputStream" and it works fine. What is special about paths in the class FileInputStream?
Try this code:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadFromExcel {
public static void main(String[] args) throws FileNotFoundException {
File f=new File("C:"+File.separator+"Personal"+File.separator+"test.xlsx");
FileInputStream file=null;
if(f.exists()) {
file = new FileInputStream(f);
//rest of code
} else{
System.out.println("The file does not exist!Please enter correct filename!");
}
}
}
I have 3 things to point out:
Firstly you have not added a try/catch block.My IDE simply does not let it compile!
Using File.separator is the more recommended way instead of using "\" or "/" if you are using file paths as they depend on OS.They make your code more portable.
Checking that the file whether exists or not using f.exists() would let you know if actually the file you are trying to pass as parameter to FileInputStream exists.
Sure that would help!!
Maybe the first two '\' only represent one '\', so you can use file path as "C:\\Personal\test.xlsx"
Suggestion: call File.canRead() to see if you have permissions to open the file.
Java new File() says FileNotFoundException but file exists
There are three cases where a FileNotFoundException may be thrown.
The named file does not exist.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
Related
I have had two years experience in Java but have not touched in a year therefore a little rusty.
I am trying to reading a text file line by line using Java8 (the new way).
Based on a forum I have read I am using the following code:
package codeTest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String filename = "RouterInfo.txt";
try(Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(System.out::println);
} catch(IOException e) {
e.printStackTrace();
}
}
}
But no matter what I try I keep getting a java.nio.file.NoSuchFileException.
Here is a picture of my file directory in eclipse:
Can anybody help?
Your text file is in src/codeTest folder so it should be
"src/codeTest/RouterInfo.txt"
Your Java code is correct. Only your RouterInfo.txt is in the wrong place. Just put it into your project directory instead of into src.
Replace filename string with "./src/RounterInfo.txt".
The text file should not be put in the src folder but in the folder that contains src.
Therefore the new folder path should be:
Answer/sample.txt
Answer would be the name of the folder containing src.
I'm trying to make a simple program to copy file of any type. I write the code as below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
public class CopyExample {
public static void main(String[] args) throws Exception {
File f = new File("image.jpg");
FileInputStream is = new FileInputStream(f);
FileOutputStream os = new FileOutputStream("copy-image.png");
byte[] ar = new byte[(int)f.length()];
is.read(ar);
os.write(ar);
is.close();
os.close();
}
}
I already tested this code for .txt , .jpg , .png, .pdf It is working fine.
But I want to ask is it fine? or is there any other way to do this in better way?
Copying a file is not about its file extension or type. It is about its content. If file is so big maybe computer's memory will not be enough.
Apache's FileUtils may be useful for your question.
this Q&A may help you.
And this article is about your question
Java 7 provides Files class that you could use to copy a file
Files.copy(src,dest);
Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.
Scanner Class couldnt find the file
I use NetBeansIDE, and the test.txt is in the folder path: D:\netbeans project works\ReadFile\src\readfile\test.txt
in the same folder the readfile.java exsist.
the code is as below.
It generates file not found.
package readfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws IOException , FileNotFoundException
{
Scanner scanner = new Scanner(new File("test.txt"));
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
}
}
output:-
run:
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at readfile.ReadFile.main(ReadFile.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Add the following before creating Scanner class:
System.out.println(new File("test.txt").getAbsolutePath());
It will show you where JVM expects to find the file and whether it is the folder you expect as well.
Also check file permissions. But most likely it is a problem with default JVM directory.
Ahhh you aren't specifying the full file path. When a file path is abbreviated (i.e. test.txt), java assumes that the file is in the same directory as the source code that is running it. So either specify the full path, or move the file.
Move it to the ReadFile directory, i.e. the root of the project
The test.txt file should be in the folder where the file readfile.class exists.
I am aware that this problem has been reported a long time ago, however, I have faced a similar obstacle and then the proposed solutions didn't work, thus I decided to post another answer.
Try using try... catch clause. For instance, only then my code has become compiled by NetBeans.
what worked for me was removing .txt extension from the file name and using . to specify current directory (example shown below).
Scanner scanner = new Scanner(new File("./test"));
I need to programatically change the encoding of a set of *nix scripts to UTF-8 from Java. I won't write anything to them, so I'm trying to find what's the easiest|fastest way to do this. The files are not too many and are not that big. I could:
"Write" an empty string using an OutputStream with UTF-8 set as encoding
Since I'm already using FileUtils (from Apache Commons), I could read|write the contents of these files, passing UTF-8 as encoding
Not a big deal, but has anyone run into this case before? Are there any cons on either approach?
As requested, and since you're using commons io, here is example code (error checking to the wind):
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) throws IOException {
String filename = args[0];
File file = new File(filename);
String content = FileUtils.readFileToString(file, "ISO8859_1");
FileUtils.write(file, content, "UTF-8");
}
}