I use FileWriter for create a file.
I have an error Directory does not exist
I think that FileWriter create the directory if it did not exist
FileWriter writer = new FileWriter(sFileName);
java.io.FileWriter does not create missing directories in the file path.
To create the directories you could do the following:
final File file = new File(sFileName);
final File parent_directory = file.getParentFile();
if (null != parent_directory)
{
parent_directory.mkdirs();
}
FileWriter writer = new FileWriter(file);
From the API documentation, we can conclude that FileWriter does not create a DIR if it does not exist:
FileWriter
public FileWriter(String fileName)
throws IOException
Constructs a FileWriter object given a file name.
Parameters:
fileName - String The system-dependent filename.
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
Related
I created two files in this program: "OutputFile.txt" and "InputFile.txt". When I run my code, it displays an error called "java.io.FileNotFoundException" but it created "OutputFile.txt" in my system but not "InputFile.txt"
Why is that?
public static void main(String[] args) throws IOException{
// 2 File objects are created: outFile and inFile, this will create text files in my system
File outFile = new File("OutputFile.txt");
File inFile = new File("InputFile.txt");
// These FileWriter Objects are created to allow the File Object to be writable to readable
FileWriter out = new FileWriter(outFile);
FileReader in = new FileReader(inFile);
// these closes files after use in program
out.close();
in.close();
}
2 File objects are created: outFile and inFile, this will create text files in my system
The first part of this is correct; the second is not. Creation of a File object is not creation of a file; new File(...) just makes an object that stores a path, basically, and does not touch the disk in any way. Per docs, a File object is
An abstract representation of file and directory pathnames.
FileWriter and FileReader do touch the disk. FileWriter writes to a file, and will create one if it does not exist; FileReader does not write, it reads — and if the file does not exist, it complains.
I am trying to write some coordinates to a file and later read it in as a string. So I need to have them written to file attached...without space or a new line, but my code writes only the first coordinate, that is pos_Let, but does not write pos_Num at all, not even with a space or on a new line.
So how can I get the code to write to file pos_LetposNum like that? Obviously I mean their references ;) ..thanks in advance
protected void writeCoordtoFile () throws IOException
{
File file = new File("FermiPresentCoord.txt");
boolean yes = file.createNewFile() ;
//boolean yes = exists();
if (yes == true)
{
// create a FileWriter Object
FileWriter writer = new FileWriter(file, true);
// Writes the content to the file
writer.write("");
writer.flush();
writer.write(pos_Let);
writer.flush();
writer.write(pos_Num);
writer.close();
}
else
{
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter out = new FileWriter(file);
// Writes the content to the file
out.write(pos_Let);
out.flush();
out.write(pos_Num);
out.flush();
out.close();
}
}
Quoting the method createNewFile():
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
Returns:
true if the named file does not exist and was successfully created; false if the named file already exists
in your case, you first create the file, and createNewFile() returns true, so you go to the if block, appending the line to the current file. Then, createNewFile() returns false, since, the file exists! So, you go to the else block, and create the file again from scratch...
So, basically, just inverse the if with else, and don't call createNewFile() twice... With the least possible changes (so that you do not get confused) here is my simple suggestion:
protected void writeCoordtoFile () throws IOException
{
File file = new File("FermiPresentCoord.txt");
boolean fileDoesNotExist = file.createNewFile() ;
//boolean fileDoesNotExist = file does **not** exist!
if (fileDoesNotExist)
{
// create a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write(pos_Let);
writer.write(pos_Num);
writer.close();
}
else
{
// creates a FileWriter Object
FileWriter out = new FileWriter(file,true);
// Writes the content to the file
out.write(""); //not sure why you need that...
out.write(pos_Let);
out.write(pos_Num);
out.close();
}
}
I can not find out why you are checking the existence of the output file. Because, when you are using FileWriter if the file specified in the path does not exist, it would create it and open a character output stream to it. Also if it exists in that path, only opens the output stream and it is ready to write into.
Try the following code and see whats happening when you run it more than one times:
float posLat = 156.23589965f;
float posLon = 12.987564f;
File file = new File("c:/FermiPresentCoord.txt");
FileWriter writer = new FileWriter(file, true);
writer.append(posLat+",");
writer.append(posLon+",");
writer.flush();
writer.close();
There is no need to invoke the file.createNewFile() and/or checking the for the existence of the file when you want to write into it.
The second argument for the FileWriter constructor is append flag. So every time you create an output stream to a file with FileWriter(file, true) constructor it automatically appends to the data of the file.
Good Luck.
I have the below java code in which i am passing a file name to the the calling method lets say below code is initially the code is
File file = new File("C:\\oabc.csv");
String filename = file.getName();
s = getFileExtension(file) ;
if (s.equalsIgnoreCase(".csv"))
{
convertcsvtoexcel(filename);
}
now since there is an csv file that is being passed so it will call the method to convert the csv to excel till that stage i have tried to debug i am getting the filename but below is the convert code that is called in which it not find the filename throwing an exception that file not found exception
public static void convertcsvtoexcel(String filename) throws Exception {
ArrayList arList=null;
ArrayList al=null;
String thisLine;
int count=0;
FileInputStream file1 = null ;
file1 = new FileInputStream(new File(filename));
DataInputStream myInput = new DataInputStream(file1);
int i=0;
But it in the above code it throws the error at line file1 = new FileInputStream(new File(filename)); saying that it does not found file abc.csv at the specified location
getName() returns the file name without any directory information, so in
String name=file.getName();
File file2=new File(name);
file2 and file are not pointing to the same file, unless file is in the current directory.
In your code, pass a File object to your method to avoid path conversion issues.
You should use convertcsvtoexcel(getPath()).
in the following line of code you are just passing the file name.To make it work pass the entire file path + file name.
file1 = new FileInputStream(new File(filename));
file1 = new FileInputStream(new File("C:\\oabc.csv")); this should work.
This question already has an answer here:
Why FileWriter doesn't create a new file?
(1 answer)
Closed 8 years ago.
So I have a code snippet as follows. Im trying to find out why it throws a FileNotFoundException.
File file= new File (WORKSPACE_PATH+fname);
FileWriter fw;
if (file.exists())
{
fw = new FileWriter(file,true);//if file exists append to file. Works fine.
}
else
{
fw = new FileWriter(file);// If file does not exist. Create it. This throws a FileNotFoundException. Why?
}
Using concatenation when creating the File won't add the necessary path separator.
File file = new File(WORKSPACE_PATH, fname);
You need to add a separator (Windows : \ and Unix : /, you can use File.separator to get the system's separator) if WORKSPACE_PATH does not have one at its end, and manually creating the file with its parent directories might help.
Try this if WORKSPACE_PATH does not have a separator at its end :
File file = new File(WORKSPACE_PATH + File.separator + fname);
And add this before fw = new FileWriter(file);
file.mkdirs(); // If the directory containing the file and/or its parent(s) does not exist
file.createNewFile();
This might work:
File file= new File (WORKSPACE_PATH+fname);
FileWriter fw;
if (file.exists())
{
fw = new FileWriter(file,true);//if file exists append to file. Works fine.
}
else
{
file.createNewFile();
fw = new FileWriter(file);
}
I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}