This question already has answers here:
How do I check if a file exists in Java?
(19 answers)
Closed 2 years ago.
I have created an executable jar file. User is required to put in his/her name and save it in order to proceed. This requires creation of a file, but due to *.txt at gitignore it will not be stored in git. I would like to know the proper way to create a file, so that user will be able to put in his name and proceed. What should I add besides:
File yourFile = new File("Name.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false);
try {
BufferedWriter reader = new BufferedWriter(new FileWriter(new File("Name.txt"), true));
reader.write(Data);
reader.newLine();
reader.close();
} catch (IOException E) {
System.out.println("Error is " + E);
}
You usually store and manage code in git. You usually don't store binaries and runtime data in git.
To my eye the code is lacking checking the existence if the file already exists. Please look here for more info: How do I check whether a file exists without exceptions?
By the way. Please don't do things like:
BufferedWriter reader (...)
It's not a reader. It's a writer.
Related
This question already has answers here:
why new FileWriter("abc.txt") creates a new file and new File("abc.txt") does not?
(6 answers)
Closed 3 years ago.
I use new File() to create a file in memory and then I want to write on it but not creating file in disk.
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("This is the text of my file");
writer.close();
I want it to not create a file on disk.
File is a filelocation, so it doesn't create a file, it point to one.
however when you create a filewriter, and write something to it (like in this example a with a wrapper class buffered writer)
then you will create an file, especially in your case you close the bufferedwriter, which prompts it to flush it's buffer to the filewriter. That filewriter is what's makes your file, cause it needs to write some data to the file called 'hello.txt'
the placement in your tomcatfolder(bin) is because that's what your current dir for the java application is.(startup of you jvm, and without changes to catalina.bat or .sh thats also your working dir)
equivalent is that you would touch a file in console, your working dir is where the file points toward, and unless you specify the full pathname the working directory will be used to place your file in.
If your looking for storing 'file' data in memory then take a look at https://stackoverflow.com/a/17595282/11515649
In my java code, I am using renameTo method to rename the file. I am able to do it successfully if the file is closed physically. But I am unable to do so if the file I am trying to rename is open.
How do I close the file thru code?
This is the code :
File file = new File("/users/abc.txt");
File newFile = new File("/users/xyz.txt");
if (file.renameTo(newFile)) {
System.out.println("File rename success");
} else {
System.out.println("File rename failed");
}
Thanks in advance.
You cannot close a file in Java that is opened by another user. It is highly platform dependant, it is impossible if that user/process has higher priviledges then your process, and the user editing it might hava data loss, if he is in the process of editing that file in an Editor. Don't ever do that.
The only way would be to wait until the file has been closed by that other user like that, however, I still discourage from doing so. If you have to use that file, just exit your application with an error.
File file = new File("/users/abc.txt");
File newFile = new File("/users/xyz.txt");
try {
while (!file.renameTo(newFile)) {
Thread.sleep(10_000); // wait 10 seconds
}
} catch (InterruptedException ex) {
// ignore
}
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 7 years ago.
I want to write particular string in a file after a string. My file has this already -
##############################
path :
I need to write the String /sdcard/Docs/MyData after path :
Could anyone tell me how I could achieve this?
If I understand correctly you mean to append your path at the end of your file.
If so the use of a FileWriter is a good way to do it.
new FileWriter("Your path", true)
Notice that the boolean true in this case indicates that you want to append to your file, removing this altogether or using false instead would mean you want to overwrite the file.
An example for your case:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C:/YourEpicPath/ThisFileNeedsSomeAppending.txt", true)))) {
out.println("/sdcard/Docs/MyData");
}catch (IOException e1) {
//exception handling left as an exercise for the reader
}
Here is some documentation if you need for android, normally there shouldn't be any big differences.
This question already has answers here:
How do I check if a file exists in Java?
(19 answers)
Closed 7 years ago.
I would like to know how to open a file in java for writing, but I only want to open it if it exists already. Is that possible? I've searched around and found two suggestions so far which both don't meet my needs. One was to open a file for appending. The problem there is that if the file doesn't exist it will create it. The second was to use file.exists() first. That of course is not a valid solution as the file may exist when I call file.exists() but then not exist when I go to open the file. I want something similar to the Windows API OpenFile() in which I can pass OPEN_EXISTING flag such that the call will fail is the file doesn't exists. Does anything like that exist in java?
Only editing question because it was marked duplicate. Not sure why. I thought I was pretty specific about the other answers and why they were not sufficient.
So I'll restate, I want to open a file for writing. I want the open to fail if the file doesn't already exist.
exists() returns true if the file path is a valid directory even if the file isn't there. You can get around this by using:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {/*Do whatever*/}
or use:
File f = new File(filePathString);
if f.isFile() {/*Do whatever*/}
Just catch the FileNotFoundException that is thrown:
try (FileInputStream fis = new FileInputStream(file))
{
// ...
}
catch (FileNotFoundException exc)
{
// it didn't exist.
}
Solutions involving File.exists() and friends are vulnerable to timing-window problems and therefore cannot be recommended. They also merely duplicate what the OS already has to do, but at the wrong time, so they are a waste of time and space. You have to deal with IOExceptions anyway, so do that.
No there is nothing like that In Java.... Core library
You should be able to wrap your logic in a if statement that names use of the file.exists() method. If you do the check just before opening the file the you would be extremely unlucky if someone has deleted the file in-between. The method that checks if the file exists and the code to open the file and lock it should run in milliseconds..
Eg
If (file.exists() {
//Your Code goes here..
} else {
System.out.Print("missing file");
}
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.