I'm trying to define a File in Java with a txt file called "helloworld". I've placed this file in a resources folder and when making the file I defined it like this:
File file = new File("/helloworld");
However I get this error when compiling
Exception in thread "main" java.io.FileNotFoundException: /helloworld
(No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at Tests.main(Tests.java:15)
This is the entire code I am trying to execute if that helps troubleshoot this issue
// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
public class Tests
{
public static void main(String[] args)throws Exception
{
File file = new File("/helloworld");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Thank you for the help!
public File(String pathname)
Creates a new File instance by converting the given pathname string
into an abstract pathname. If the given string is the empty string,
then the result is the empty abstract pathname.
You are trying to create a new File instance but the file called helloworld is not found or some other reasons. That's why you get the error,
Exception in thread "main" java.io.FileNotFoundException: /helloworld
The named file does not exist.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
You say that you try to define a file but your code seems to read. Try below one if you want to create a file,
import java.io.*;
import java.nio.charset.StandardCharsets;
class TestDir {
public static void main(String[] args) {
String fileName = "filename.txt";
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), StandardCharsets.UTF_8))) {
writer.write("write something in text file");
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is easy to diagnose: The path you specified starts with a slash, so it means that the file is expected to be located at the root directory of the filesystem. You'd better strip off the leading slash, and:
Either start your program at the same directory the file is at.
Either specify an absolute/relative path in your code when instantiating the File object.
If the file is in a resources folder and is intended to be bundled with your program, you need to treat it like a resource, not a file.
This means you should not use the File class. You should read your data with the Class.getResource or Class.getResourceAsStream method:
BufferedReader br = new BufferedReader(
new InputStreamReader(
Tests.class.getResourceAsStream("/helloworld")));
This becomes especially important if you want to distribute a program as a .jar file. A .jar file is a compressed archive (actually a zip file with different extension) which contains both compiled class files and resources. Since they are all compressed into one .jar file, they are not individual files at all, so there is no way the File class can refer to them.
Although the File class is not useful for what you’re trying to do, you may want to research the concept of absolute file names and relative file names. By starting a file name with /, you are specifying an absolute file name, which means you are telling the program to look for the file in a specific place—a place where the file almost certain will not reside.
Try bellow to know where is the folder or file's path, which your program is looking for
System.out.println(file.getAbsolutePath());
With
File file = new File("/helloworld");
I think your program is looking for c:\helloworld, and there is no file or folder's name is helloword in your C drive
If you put the helloword.txt into C drive, and
File file = new File("C:\\helloworld.txt");
FileNotFoundException will disappear.
Related
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("----------Start------------------");
URL resource = Main.class.getClassLoader().getResource("test.txt");
System.out.println("resource: "+ resource.getPath());
File file = new File(resource.getPath());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
System.out.println("----------End------------------");
}
}
If I run this code from IDEA - all work
----------Start------------------
resource: /D:/javaHz/target/classes/test.txt
1
2
3
4
5
----------End------------------
Process finished with exit code 0
if I reun from java -jar - I get error
D:\hz>java -jar hzTest-jar-with-dependencies.jar
----------Start------------------
resource: file:/D:/hz/hzTest-jar-with-dependencies.jar!/test.txt
Exception in thread "main" java.io.FileNotFoundException: D:\hz\file:\D:\hz\hzTe st-jar-with-dependencies.jar!\test.txt (Syntax error in file name, folder name, or volume label)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at test.Main.main(Main.java:15)
I do not want use getResourceAsStream
new File(resource.getPath()) won't work because file:/D:/hz/hzTest-jar-with-dependencies.jar!/test.txt isn't really a filesystem path.
Since the file is part of jar file (a zip archive in fact), there is no valid filesystem path that would point to it.
The standard way is to use getClassLoader().getResourceAsStream("test.txt");. You'll either have to modify your application so that it can read from classpath resources or URLs, or use getResourceAsStream() to copy the resource to a temporary file on filesystem and then point to it.
The correct way to translate a URL to a absolute path that you can use outside Java is this:
import java.net.URL;
import java.nio.file.Paths;
URL resource = Main.class.getClassLoader().getResource("test.txt");
String absolutePath = Paths.get(resource.toURI()).toAbsolutePath());
This only works right if the resource comes from a file:// url - if your application was built as a jar file, it won't work, as other applications cannot look inside a jar file directly.
It look a bit convoluted, and it is. To break this down a bit:
URL resource = ...;
URI uri = resource.toURI();
Path path = Paths.get(uri);
String absolutePath = path.toAbsolutePath();
File file = new File(resource.getPath());
Bzzt. Resources are not files. You have a URL. Use its input stream directly.
I have an excel file which I have kept in a subfolder of my main package.
I want to read that file. When I read it using InputStream, it file is easily detected but when I read using FileInputStram or File file = new File(filepath) I get the error that the file is not found.
Can anyone help me in reading the file using FileInputStram or File file = new File(filepath)?
The code what I wrote to read the file is
File file = new File("upgradeworkbench/Resources/workbookOut.xlsm");
and
FileInputStream inp = new FileInputStream("upgradeworkbench/Resources/workbookOut.xlsm");
I tried with / in the beginning of the path but still it didn't work.
When working with File class you need to provide either absolute or relative path. Absolute path is the full file path e.g. C:\workbookOut.xlsm
In relative paths, there is a concept of a working directory and it's represented by a . (dot) and everything else is relative to it.
Try either giving the full path or the relative path.
File file = new File("./upgradeworkbench/Resources/workbookOut.xlsm");
If your file in classpath then try below code
package mypack;
import java.io.*;
public class TestPath
{
public static void main(String[] args) throws Exception
{
InputStream stream = Test.class.getResourceAsStream("/workbookOut.xlsm");
System.out.println(stream != null);
stream = Test.class.getClassLoader()
.getResourceAsStream("workbookOut.xlsm");
System.out.println(stream != null);
}
}
If your file in same package then use the below line it will work
URL url = getClass().getResource("workbookOut.xlsm");
File file =new File(url.getPath());
I am creating a file like this (I am sending arg[0] as the name of the file to be created).
No file is created I searched through the source of the project and found nothing, why?
import java.io.File;
public class Test {
public static void main (String [] args)
{
File f=new File(args[0]);
}
}
Try with
File f=new File(args[0]);
f.createNewFile();
File is just a representation of the path. You need to actually open an output stream with that file and write to that for a file to be created.
This is normal.
A File is an abstract object. It may, or may not, refer to an existing resource on the filesystem.
But since this is 2015, drop File, use java.nio.file instead:
final Path path = Paths.get(args[0]);
Files.createFile(path);
But really, you shouldn't use File in 2015. Seriously. Yes, .createNewFile() exists on File but... Well, read the page. In short: returns a boolean, need to check the return value, if false, SOL, you can't even diagnose.
Edit: a page to learn how to use java.nio.file: here
(shameless self-advertising for both links, sorry for that)
Just creating file object does not create physical file on disk.Actual file is created with f.createNewFile() as explained in below demo
When yo do File file=new File(args[0]); file just represents the java object not the file object on file system
Here is demo for basic file create and delete operations
public class FileDemo {
public static void main(String[] args) {
File f = null;
try{
// create new file
f = new File("test.txt");
// tries to create new file in the system
f.createNewFile();
// deletes file from the system
f.delete();
}catch(Exception e){
e.printStackTrace();
}
}
}
Executing new File(...) does not create a file in the file system. A File object is just a way of representing the path for a file system object that may or may not existing.
The typical way to create a file is to open a FileOutputStream or FileWriter for the file. The file is created even if you don't write anything. Other alternatives are to call File.createNewFile() or File.createTempFile(...).
I have used this reference to read a file on my project. but i need to store likewise i don't know how to do this? please help me.
for reading a file i have taken the code from the link
InputStream csv =
SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");
Like this can anyone help me with writing a file
currently I'm using this code:
Writer output = null;
output = new BufferedWriter(new FileWriter("./filename.csv"));
But it throws FileNotFound Exception at runtime
Issue is with locating file path. it works fine if i give absolute path. but it needs to be run in any computer
The FileWriter will create files as required. It doesn't have to exist already.
The only way you can get this error is if the current working directory no longer exists or you don't have permission to create a file in the directory.
Check your permissions:
Writer output = null;
if (new File("./filename.csv").canWrite()) {
System.out.println("You have not permissions");
} else {
output = new BufferedWriter(new FileWriter("./filename.csv"));
...
}
OK..Use the following code to get the path of file:
String path = System.getProperty("user.dir");
FileWriter fw = new FileWriter(path+File.separator+"filename.csv");
EDIT
Here is a Demo Code that is creating file "pqr.txt" in package myPackage. Given that I am executing the class file using command java myPackage.AccessCheck i.e from one directory above the mypackage.
package myPackage;
import java.io.FileWriter;
import java.io.File;
public class AccessCheck
{
protected void callme()
{
try
{
String name = System.getProperty("user.dir")+File.separator+AccessCheck.class.getPackage().getName()+File.separator+"pqr.txt";
System.out.println(name);
FileWriter fw = new FileWriter(name);
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String st[])
{
AccessCheck asc = new AccessCheck();
asc.callme();
}
}
Instead of calling getResourceAsStream(), call class.getResource() or classLoader.getResource(). These functions return a URL giving the location of the resource. If the resource is a plain file on the filesystem, the URL will be a file: URL.
Once you have the URL, you can convert it to a URI and pass it to the File constructor which takes a URI. Then you can use the File object to open the file.
Note that getResource() can return URLs that the File constructor can't deal with. For example, if the resource is found in a jar file, then the URL might look like this:
jar:file:/C:/path/to/JDK/lib/vm.jar!/java/lang/Object.class
The File constructor can't deal with URLs like this. This may or may not be a concern for you.
I'm sure I'm missing something basic here.
I'm trying to create a new file on my drive, but I'm getting an error:
Exception in thread "main" java.io.FileNotFoundException: C:\ProgramData\msena\test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileReader.<init>(FileReader.java:55)
at net.meosoft.relatetoit.core.HibernateSessionFactory.main(HibernateSessionFactory.java:89)
My code at the moment is:
final File file = new File("C:\\ProgramData\\uname2\\test.txt");
final BufferedReader in = new BufferedReader(new FileReader(file));
while(in.ready()) {
System.out.println(in.readLine());
}
in.close();
What's wrong at the moment? I want to just read, even if it's there (so file should be made).
Java doesn't automatically check that File() exists, nor will it automatically create it if you ask it.
You'll need to do one of the following:
Add in a check for the file's existence: if(file.exists()) { ... }.
Add in a check, similar to above, but then if it doesn't exist, call: file.createNewFile();. This will make a new file on the file system for you to use.
If that still doesn't work, I'd check you have write permissions to that directory. :)
The File class represents the path to a file, not the file itself. If the file does not exist (!File.exists()), an exception will be thrown when you try to access it. Make sure the path to the file is correct and that you have permission to read from that location.
If you want to create the file, you can use File.createNewFile().
this is the method to create file.
Formatter output;//pointer to an object that will write to a file
public void createFile(){
try{
output = new Formatter("C:\\ProgramData\\uname2\\test.txt");
//test.txt is the name of the file to be created
//create file in the same folder called test.txt
//if existed overwrite it
}
catch(FileNotFoundException e){
System.err.println("Error creating file"+e.getMessage());
}
call createFile() in the main
CreateTextFile file = new CreateTextFile();
file.createFile();
Check your file name. It should not contain any colon.