Change file name and its extension before output it Java - java

Lets say I've got a file in D: which has a filepath as:
D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01
at the moment the name of this file is not meaningful. It doesn't have a format. I would like to have the ability to create file object from the above filepath in Java and change its name and format before writing it into bytes. The new path could be as following:
D:\work\2012\018\08\mywork.pdf
After the changes have been made, I should still be able to gain access to the original file per normal.
I already know the type of the file and its name so there won't be a problem getting those details.

Just rename the file:
File file = new File(oldFilepath);
boolean success = file.renameTo(new File(newFilepath));
You could also just give a filename and use the same parent as your current file:
File file = new File(oldFilepath);
file.renameTo(new File(file.getParentFile(), newFilename));

It's not really clear what exactly you want; I hope this answer is useful to you.
Suppose you have a java.io.File object that represents D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01, and that you want to have a File object that represents D:\work\2012\018\08\mywork.pdf. You already know the new filename mywork.pdf but you want to get the directory name from the original File object. You can do that like this:
File original = new File("D:\\work\\2012\\018\\08\\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01");
// Gets the File object for the directory that contains the file
File dir = original.getParentFile();
// Creates a File object for a file in the same directory with the name "mywork.pdf"
File result = new File(dir, "mywork.pdf");

Related

How to create a file in java without random numbers getting added to the filename and delete after use?

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();

Java - create file and dir

Assume final String fname = "/dir1/dir2/fname.ext". I do not wish to parse the string recursively in order to create the directories if they do not exist, and only then write to a file. I wish to use the given string, fname, for creating the directories and file if each of which does not exist.
This is the code you are looking for:
File myFile = new File("/dir1/dir2/fname.ext");
myFile.getParentFile().mkdirs();
// do your writing being sure the parent directories exist.
You can use mkdirs to create the path.
File f = new File("/dir1/dir2/fname.ext");
f.getParentFile().mkdirs();
And then work on the file itself.

Selecting txt file from any location with File Chooser in Java

I have used the Sun File Chooser Demo to choose files from my desktop or any location.
I have added the following code in the open file action:
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
log.append("Opening: " + file.getName() + "." + newline);
ReadData rd = new ReadData(); //added by me
rd.readData(file.getName()); //added by me
} else {
log.append("Open command cancelled by user." + newline);
ReadData class contains readData method which will take the file name and with BufferedReader will read the contents of the file line by line.
But after choosing the file with file chooser it is not able to open the file from my desktop.If I place the file inside the project folder it is able to open the file without any code change.
What modification in code I need to do so that it can choose and open file from any location?
Thanks
You are passing only the file's name, not the complete path, to your ReadData class. So, your ReadData class is not going to know in which directory the file is - it will try to find it in the current directory (whatever that is at the moment).
Instead of just passing the name of the file, pass the whole path:
rd.readData(file.getPath());
Better yet, change your ReadData.readData() method so that it takes a File instead of a String, and pass it the File object that you get back from the file chooser:
rd.readData(file);
getName() only gets the last segment of the file without any path information. If the working directory of your Java application isn't the exact directory that holds that file, that won't work.
Why doesn't your ReadData just take a file? All file input mechanisms built into Java will accept a File (e.g. FileInputStream, FileReader). Otherwise use getPath() I guess.
You are only passing the name of the file to the readData() method.
So if your file is stored at C:\Users\JavaBits\Project\Java\file.txt, your readData() method is only getting file.txt so it can't find the file. You should do this:
rd.readData(file);
This will have the relative path in it.
use file object to open inputstream instead using its name. such as:
BufferedReader br = new BufferedReader(new FileInputStream(file));
modify your method readData to accept File object instead String, and use this object to open BufferedReader.

Reading .txt file from another directory

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

Android writing to a CSV file via OpenCsv

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?

Categories

Resources