How to create a file & folder in Java? [duplicate] - java

This question already has answers here:
create a text file in a folder
(4 answers)
Closed 9 years ago.
Okay, updated this right now
As of now I have this:
File saveGame = new File(Config.saveDir,Config.saveName);
Now how would I create that into a text file? My saveDir has already been created (mkDir), and my saveName is defined as "xyz.txt", so what method do I use to create this file (and later add text into it)?

new File(...) doesn't crete a file on disk, it only creates a path for a Java program to use to refer to a file that may or may not exist on disk (hence the File.exists() method).
Try userFile.createNewFile(); to actually create the file on disk.
To make the directory you would need to use the File.mkdirs() method, but don't call it on userFile or it will make a directory with the Savegame.txt in it.
Edit:
File dir = new File(Config.userpath + "/test/");
File file = new File(dir, "," + Config.name + " Savegame.txt");
dir.mkdir(); // should check to see if it succeeds (if(dir.mkdir())...)
file.createNewFile(); // should also check that this succeeds.

Related

How to check if file exists knowing only file name? [duplicate]

This question already has answers here:
How do I check if a file exists in Java?
(19 answers)
Closed 3 years ago.
In Java using Maven project we may read file's content as a stream by knowing only file's name, for example:
InputStream in = getClass().getResourceAsStream("/" + fileName);
But is there way to check if the file exists without indicating the whole path, just passing file name?
file.exists() can be used to check whether such a file exists or not.Like following:
File file = new File("filepath");
if(file.exists()){
// Do your stuff
}

Java: Referencing a file after being packaged (jar), getResourceAsStream? [duplicate]

This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!
If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);

Get files inside folder [duplicate]

This question already has answers here:
How to read all files in a folder from Java?
(33 answers)
Get a list of resources from classpath directory
(15 answers)
Closed 6 years ago.
I am trying to read the content of the folder of my Java EE Spring application, but it always return me null. The folder I want is under src/main/resources folder and it`s called context. I try doing it this way :
File file = new File("src/main/resources/context")
But it always return me null for file.
You can use one of the following:
File file = new File("src/main/resources/context");
String[] list = file.list(); // returns an array of all file names in the context folder.
OR
File file = new File("src/main/resources/context");
File[] listFiles = file.listFiles(); // returns an array of all "file objects" for all files in the context folder.
Hope this helps!

How to change file path location in java.io.File object [duplicate]

This question already has answers here:
What is meant by immutable?
(17 answers)
Closed 3 years ago.
The question says it all.
I have a File object which is pointing to /home/user/filename1.
If I call file.getAbsolutePath() then it would return /home/user/filename1
My question is that -
Can we change the path inside file object to a different location?
If yes, then how?
Thanks
"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. "
From the File javadoc.
I had developed a code to rename the file and I have to save the file in the same location recursively. I think the below code helps you out upto some extent. I have to replace "-a" in my filename and save it in the same folder. If needed in place of "destPath" you can give the destination path of your string path. I think this might help you.
File oldfile =new File(file.getAbsolutePath());
String origPath = file.getCanonicalPath();
String destPath = origPath.replace(file.getName(),"");
String destFile = file.getName();
String n_destFile = destFile.replace("-a", "");
File newfile =new File(destPath+n_destFile);
A file is internally nothing else other then a string holding the path to the file. So no this is not possible. Why would you even want to do something like this? Unless you have moved the file to another location?
As someone noted before, File is immutable as many of java API classes. Maybe what you want is to copy a file from somewhere to some other place? Have in mind that a File object has no actual binding to the contents of the file, and will not allow you modifying or moving it.
Have a look at Apache Commons IO
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
Here you have a useful library to deal with files.

file.exists() returning false when the file does exist

In an Android application I'm working on, the user should be able to create a new CSV file on the SD card, named using text they input in an EditText.
The problem is that after instantiating the File using the directory and filename, file.exists() returns false, even when the file does indeed exist at that location. I have browsed to SD card using an Android file browser and through Windows Explorer, and the file does exist.
Is this the correct way to check if the file already exists, and if so, what am I missing so that it returns true when it exists?
String csvname = edittext.getText().toString() + ".csv";
File sdCard = Environment.getExternalStorageDirectory(); //path returns "/mnt/sdcard"
File dir = new File (sdCard.getAbsolutePath() + "/Android/data/" + getPackageName() + "/files/"); // path returns "/mnt/sdcard/Android/data/com.phx.license/files"
dir.mkdirs();
File file = new File(dir, csvname); //path returns "/mnt/sdcard/Android/data/com.phx.license/files/Test.csv"
if(!file.exists()) //WHY DOES IT SAY IT DOESN'T EXIST WHEN IT DOES?
{
...
}
If you use createNewFile it will only create a file if it does not already exist.
Java Files Documentation
public boolean createNewFile()
throws IOException
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
Throws:
IOException - If an I/O error occurred
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file
Since:
1.2
Creating a new file object like so new File(dir, csvname); does not create a new file in the file system.
You need to write data to it first.
I had the exact same issue but with yarn on hadoop where a spark job was trying to execute a command.
It was a file permission issue. I troubleshooted it by code like below which is in scala. exists and notExists both return false, which means the jvm is not able to tell if the file exists or not.
import java.nio.file.Path
import java.nio.file.Paths
val path = Paths.get(fileLocation);
println(":"+ Files.exists(path)+ ":" + Files.notExists(path))

Categories

Resources