Java File manipulation - java

So I have an application with a JFileChooser from which I select a file to read. Then I change some words and write a new file. The problem that I am having is that when I write the new file it's saved in the project directory. How do I save it in the same directory as the file that I chose using the JFileChooser. Note: I don't want to use the JFileChooser to choose the location. I just need to save the file in the same directory as the original file that I read.

You choose a file like this:
File fileToRead = JFileChooser.getSelectedFile();
Then you read and change the content and write it back to the same location with a different name:
File fileToWrite = new File( fileToRead.getParent(), "newName.txt" );

Related

How can I create a file with limited privilege in Java?

I want to create a File using Java, that allows the program to modify the contents, however any external user should not be able to go to the path and manually delete or update that file. In other words I want to revoke privilege from users to be able to delete/update that file.
For example:
path = "C:\\newfile.txt"
File file = new File(path);
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("hello world");
The above code allows the program to write hello world to the file.
I want to make sure that no one can delete the file manually from "C:\". How do I do that?

Change file name and its extension before output it 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");

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