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());
Related
I have to create a temp file in the /tmp directory the code that I am using is adding random numbers to the filename. I have to use the name of the file in order to do something. With the random number, I am not able to use that file. The code I wrote is :
File dir = new File("/tmp");
String prefix = "temp";
String suffix = ".txt";
File tempFile = File.createTempFile(prefix, suffix, dir);
After using the file with the correct file name I also have to delete it how can I do that?
If you need to access the File again, you can store the path of the file to be accessed at another time.
You can get the absolute path file using:
tempFile.getAbsolutePath();
To answer your question about deleting the file after you are finished using it, you can either use the detete() or deleteOnExit() methods of File.
If your code needs a predictable filename, and you want that file to be cleaned up automatically when the program ends, don’t use a temp file (they have a random name - it’s just how they work) but rather just use deleteOnExit() with a regular file:
File file = new File("some/filename.ext");
file.deleteOnExit();
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
I want to create a temporary file (that goes away when the application closes) with a specific name. I'm using this code:
f = File.createTempFile("tmp", ".txt", new File("D:/"));
This creates something like D:\tmp4501156806082176909.txt. I want just D:\tmp.txt. How can I do this?
In this case, don't use createTempFile. The point of createTempFile is to generate the "garbage" name in order to avoid name colisions.
You should use File.createNewFile() or simply write to the file. Whichever is more appropriate for your use case. You can then call File.deleteOnExit() to get the VM to look after cleaning up the file.
If you want to create just tmp.txt, then just create the file using createNewFile(), instead of createTempFile(). createTempFile is used to create temporary files that should not have the same name when created over and over.
Also have a look at this post which shows a very simple way to create files.
Taken the post mentioned above:
String path = "C:"+File.separator+"hello"+File.separator+"hi.txt";
//(use relative path for Unix systems)
File f = new File(path);
//(works for both Windows and Linux)
f.mkdirs();
f.createNewFile();
try regex
fileName = fileName.replaceAll("\\d", "");
The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file
I try to write to a Csv file via:
mFileWriter = new FileWriter(
"/sdcard/program/file");
mCsvWriter = new CSVWriter(mFileWriter);
At the moment it throws an exception that the file doesn't exist.
It's true that the file doesn't exist. What's the easiest way to create the file?
Does the FILE not exist, or the DIRECTORY it's supposed to go into?
If you want to create a directory structure, you can always do
File file = new File("/full/path/to/file");
file.mkdirs();
This will create any path leading up to this file that doesn't exist yet.
I suppose the missing quotes around your file name are a typo?