Check if a text file exists - java

I need to pick a text file from a folder and read the data in the file. The file is generated dynamically in that folder in the format "XXX_2010-12-06". So, first i need to check if the file is existing in the folder and if it exists the content of the file should be read.
I have the code to read the content in the text file. I need to provide the path of the file
Can anyone help me in coding this using java...

You can create a new instance of File and initiate it with the path to the file itself.
File file = new File("/a/path/to/a/file/TheFile.txt");
Once you have your File instance created you can check to see if it exists by calling the exists() method inside of File.
System.out.println(file.exists() ? "The file exists!" : "The file doesn't exist!");
I couldn't really understand what you were asking for help with. But if you edit your question to be more clear I will edit my answer to fulfill further answering.

The File class has methods for checking whether a file exists.

Related

Processing/Java File Count Issue With File Pathway (Variable Type)

Although the Title isn't very understandable I do have a simple issue. So i'm trying to write some code in a Processing Sketch (https://processing.org/) which can count how many files are in a document. The problem is, is that it doesn't accept the variable type.
File folder = File("My File Path");
folder.listFiles().size;
It says the function File(String) doesn't exist. When I try to put the file path without quation marks, it still doesn't work!
If you have a solution then please use a functioning example so that I know how it works. Thanks for any help!
As Joakim Danielson says it is constructor so you need to use new keyword.
Below code will work for you.
File folder = new File("My File Path");
int fileLength = folder.listFiles().length;
It's a constructor so you need to use new
File folder = new File("My File Path");
//To get the number of files in the folder
folder.listFiles().length;
Assuming the "My File Path" folder is inside your sketch you need to provide the path to your sketch. Luckily Processing already provides a helper function: sketchPath()
Here's an example:
File folder = new File(sketchPath("My File Path"));
println("folder.exists: " + folder.exists());
if(folder.exists()){
println(folder.listFiles().length + " files and/or directories");
}else{
println("folder does not exist, double check the path");
}
Bare in mind there's also a dataPath() function which points to a folder named data in your sketch folder. The data folder is typically used for storing external data (e.g. assets (raster or vector images/Processing font files) or raw data (binary/text/csv/xml/json/etc.)). This is useful to separate your sketch source files from the data to be loaded/accessed by your sketch.
Also, Processing has a few utility functions for listing files and folders.
Be sure to check out Processing > Examples > Topics > File IO > DirectoryList
The example includes less documented functions such as listFiles() (which returns an array of java.io.File objects based on the filters set) or listPaths (which returns an array of String objects: just the paths).
The options and filters are quite handy, for example if you want to list directories only and ignore files you can simply write simply like:
println("directories: " + listFiles(sketchPath("My File Path"),"directories").length);
For example if want to list all the wav files in a data/audio directory inside the sketch you can use:
File[] files = listFiles(dataPath("audio"), "files", "extension=wav");
This will ignore directories and any other file that does not have .wav extension.
To make this answer complete, here are a few more details on the options for listFiles/listPaths from Processing's source code:
"relative" -> no effect with the Files version, but important for listPaths
"recursive"-> traverse nested directories
"extension=js" or "extensions=js|csv|txt" (no dot)
"directories" -> only directories
"files" -> only files
"hidden" -> include hidden files (prefixed with .) disabled by default

Can't create .txt files

I have it like this:
file=new File(pathString+"/TileRecordings/",jTextField1.getText()+".txt");
and then after null checking etc...
file.createNewFile();
Thing is, if the texfield value was 'test' it would create 'text.txt' AS A FOLDER. Not an actual text file.
Is this a Ubuntu only thing? How do I force it to literally create a text file, not a folder named 'test.txt'.
Maybe try features from java.nio.file
for example:
Path temp = Paths.get(pathString+"/TileRecordings/"+jTextField1.getText()+".txt");
Files.write(temp, contentToSave.toString().getBytes());

What type of File is created when we create new File without the extension?

In java, when we create a file, we create files using the name of the extension.
For example :
File file = new File("D:/light.txt");
I would like to know what type of file format do we get when we create a file without the file extension type.
For example :
File file = new File("D:/light");
This answer assumes you're doing more than just creating a File object - that you're actually creating a file on the file system. (A File object is just a logically representation of a file system entry which may or may not exist.) If you're really just creating a File object, read EJP's answer - at that point, you've basically just got a name. That doesn't have a "type" or a "format".
The extension is just part of the name. The operating system may try to use that to display a different icon, or launch a specific application when you double-click on the icon, or whatever - but it's really just part of the name.
Fundamentally, a file consists of:
The name you specify when you create it
The bytes you write in it
Metadata such as access control
Unless you deliberately add metadata, it's typically just inherited (default permissions etc).
You can write any data in any file - just because a file has an extension of .txt doesn't mean it's definitely a text file. It could have content which is actually MP3-encoded audio data, for example. Whether the OS uses the file extension or the content to work out what to do with the file is up to the OS.
What type of File is created when we create new File without the extension?
No file is created at all, and there is only one type of File.
In java, when we create a file, we create files using the name of the extension.
Or not.
For example: File file = new File("D:/light.txt");
I would like to know what type of file format do we get when we create a file without the file extension type.
You don't. You don't get any file format at all, because you don't get a file: only a File object in memory.
For example: File file = new File("D:/light");
You can produce all the examples you want, but no file is created, and no file format.
In any case Java doesn't care about filename extensions. Your operating system might, but that's a different story.

Java File - Append pre-defined filename to a user-defined directory

I have a program that creates multiple output files e.g. daily_results.txt, overall_results.txt etc.
I want to allow the user to specify the directory that these files will be saved to using JFileChooser.
So if the user selected the directory they wanted their output to be saved to as "C:\temp\". What is the best way to append daily_results.txt to that file object. Is there a more elegant way to do this other than:
File file = new File(userDirectory.getPath() + "daily_results.txt");
Any ideas?
Apologies!
I think this can quite easily be accomplished with the JFileChoosers setSelectedFile method.

What types of files does Java's canwrite() apply to?

I need to use it to delete media files. Will canwrite() let me know if there are any locks on the file or does it only apply to text files?
canWrite() is a permissions test (i.e. a static check based on the file metadata). it has nothing to do with the file content or any file locks.
As jtanhlborn has pointed out, canWrite() is not what you're looking for. A quick way to check if a File is locked is trying to modify the file's name with renameTo and seeing whether you are successful. For example:
File file = new File("testFile.png");
boolean fileLocked = !file.renameTo(file);
In the case that the file rename succeeds, renameTo will returned true and locked will be false. Of course, the file name won't be modified since you "renamed" it to its original name.

Categories

Resources