File not being Created - java

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(...).

Related

java.io.FileNotFoundException: C:\Engines\Data.xlsx (The system cannot find the file specified)

I have an existing file in my system by the name of data but it still says The system cannot find the file specified.
I am trying to create an object of an existing class with all the methods to read an xlsx file.
My code:
public class sampletestjava {
public static void main(String[] args) {
System.out.println("learning maven");
XLS_Reader xls = new XLS_Reader("C:\\Engines\\Data.xlsx");
Error
(java.io.FileNotFoundException): C:\Engines\Data.xlsx
(The system cannot find the file specified)
Try to keep the string of absolute path like the following:
D:/eip_eclipse_workspace/codeTesting/properties/keystore_file/keystore
Which, like in your case will be:
XLS_Reader xls = new XLS_Reader("C:/Engines/Data.xlsx");
File myFile = new File("C://Engines/Data.xlsx");
FileInputStream fis = new FileInputStream(myFile);
OR
FileInputStream fis = new FileInputStream(new File("C://Engines/Data.xlsx"));
is there any class or interface like XLS_Reader ?
Even i am also learning but in my knowledge it's not.
plz update me if it is
Work with java.io concept as well
In order to work with Office files you need to understand the "Apache POI."
look for https://www.javatpoint.com/apache-poi-tutorial
Hope this helps!

Java.io.FileNotFoundException when specifying a directory

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.

My code fails at a certain point. Java File IO

I am new to Java. I programmed in C++. I am trying to work with files but my code fails when I try create a file, that is, when the program tests if the file exists, it fails, but I have already created the file.
public Schedule(String name, String event)
{
String filename= name+event+".txt";
File TimeTable=new File(filename);
if (TimeTable.exists()&&TimeTable.isFile()){
writeToFile(TimeTable,name,event,filename);
System.out.println("In constructor");
}//fails here
}
I have already created the file
If the following line is the reason you are saying this, then you're wrong.
File TimeTable=new File(filename);
This is making an abstract representation of file/directory pathnames but will not make the file if it doesn't exist.
File TimeTable=new File(filename);
TimeTable.createNewFile();
The createNewFile method will make the physical file if it doesn't already exist.

Relative path to store a file in any computer - Java

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.

File Not Created in Java

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.

Categories

Resources