How can a renamed file's path remain unchanged in java? - java

So I finally changed the name of file1 to another name. However what makes me frustrated is that the path remain unchanged!Could you please tell me why and how to deal with it since I always need the handler of file1 for further operation?Here is my sample code:
import java.io.File;
import java.io.IOException;
public class TestFile {
volatile private static File file1;
volatile private static File file2;
public static void main(String[] args) throws IOException {
file1 = new File("D:\\work\\triangle\\src\\original\\test1.java");
file2 = new File("D:\\work\\triangle\\src\\original\\test2.java");
File tmpFile;
String file2name = file2.getAbsolutePath().toString().replace("\\", "/") + ".bak";
System.out.println(file2name);
String file1name = file1.getAbsolutePath().toString()
.replace("\\", "/");
System.out.println(file1name);
tmpFile = new File(file2name);
if (!file1.renameTo(tmpFile)) {
System.err.println("file1->file2name-bak");
}
System.out.println("file1\t"+file1.getAbsolutePath().toString());
System.out.println("tmpFile\t"+tmpFile.getAbsolutePath().toString());
}
}
and I get those output:
D:/work/triangle/src/original/test2.java.bak
D:/work/triangle/src/original/test1.java
file1 D:\work\triangle\src\original\test1.java
tmpFile D:\work\triangle\src\original\test2.java.bak
How can the file1 and tmpFile yield different path?

You are misunderstanding what a File is.
A File denotes a file name / path, not the name / path of a specific file. So, when you use a File to rename a file, the pathname stored in your File object does not change. A File object is immutable.
Then is there any way to change them both?
No. The name / path encoded in a File object does not change, and cannot be changed. If you don't believe me, check the source code that is shipped with your JDK.
(The pathname state of a File is represented by the String-valued path attribute. The only places where path is assigned are the constructors, and the readObject method.)

Related

How to create a new text file based on the user input in Java?

I'm trying to create a new text file in java by having the user input their desired file name. However, when I look in the directory for the file after I run the code once, it doesn't show up.
import java.util.Scanner;
import java.io.File;
public class TestFile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
}
}
Although, when I don't have the user input a file name and just have the code written with the name in quotation marks, the file ends up being created when I look back in the directory.
File file = new File("TestFile.txt")
Why won't it create a file when I try to use the String input from the user?
You must be mistaken because just calling new File(String) won't create a file. It will just create an instance of File class.
You need to call file.createNewFile().
Adding this at the end creates the file:-
if (file.createNewFile()) {
System.out.println("File created.");
} else {
System.out.println("File already exists.");
}
The following code worked for me:
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
boolean isFileCreated = file.createNewFile(); // New change
System.out.print("Was the file created? -- ");
System.out.println(isFileCreated);
The only change made to your code is to call createNewFile method. This worked fine in all cases. Hope this helps.
From the API:
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.
Please use below code to solve your issue. You just have to call createNewFile() method it will create file in your project location. You can also provide the location where you want to create file otherwise it will create file at your project location to create file at specified location you have to provide location of your system like below
String fileLocation="fileLocation"+fileName;
File file = new File(fileLocation);
import java.util.Scanner;
import java.io.File;
public class TestFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter the desired name of your file: ");
String fileName = input.nextLine();
fileName = fileName + ".txt";
File file = new File(fileName);
file.createNewFile();
}
}
When faced with issues like this, it's really, really, really important to go hit the JavaDocs, because 90% of the time, it's just a misunderstanding of how the APIs work.
File is described as:
An abstract representation of file and directory pathnames.
This means that creating an instance of File does not create a file nor does the file have to exist, it's just away of describing a virtual concept of a file.
Further reading of the docs would have lead you to File#createNewFile which is described as doing:
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.
When you initialize your File file = new File("TestFile.txt"), it is not created yet.
You should write something to your file using FileWriter or others.
File f = new File(fileName);
FileWriter w = new FileWriter(f);
w.write("aaa");
w.flush();
or using f.createNewFile() as suggested in other answer.
Then you can see your file and its content.

using File class to create new text file

Is there a way to use the File class to create a new text file? After doing some research, I tried:
import java.io.*;
public class createNewFile
{
public static void main(String args[]) throws IOException
{
File file = new File("newfile.txt");
boolean b1 = file.createNewFile();
}
}
...but there is still no newfile.txt in my source directory. It would also seem like there would be a void method to do this, instead of having to result to a boolean. Is there a way to do what I'm trying to do with the FIle class, or so I have to result to another class?
You have created a file but apparently not in your source directory but in the current working directory. You can find the location of this new file with:
System.out.println(file.getAbsolutePath());
One possibility to control the location of the new file is to use an absolute path:
File file = new File("<path to the source dir>/newfile.txt");
file.createNewFile();
You can try like this:
File f = new File("C:/Path/SubPath/newfile.txt");
f.getParentFile().mkdirs();
f.createNewFile();
Also make sure that the path where you are checking and creating the file exists.

File I/O Confusion

First question here on StackOverflow, so apologies if this is bad. But I got a student job programming for civil engineers. My first assignment is to use JFileChooser to allow the user to specify a desired file, and then the full path of this file will be written to a txt file. I want it to automatically write to the file that this program using JFileChooser resides in. I am very confused on how to do this and haven't been able to find anything helpful on that.
My code:
public class FilePathFinder {
JFileChooser fileChooser;
String path;
public static void main(String[] args) throws IOException{
String path = null; //String that will be outputted to
//creates file chooser and its properties
JFileChooser file_chooser = new JFileChooser();
file_chooser.setCurrentDirectory(new java.io.File("user.home"));
file_chooser.setDialogTitle("Create File Path");
file_chooser.setApproveButtonText("Create Path");
file_chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
file_chooser.setAcceptAllFileFilterUsed(false);
if (file_chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
path=(file_chooser.getSelectedFile().getAbsolutePath());
}
//Writes path name to file
String user_home_folder = System.getProperty("user.home");
System.out.println(user_home_folder);
File path_file = new File(user_home_folder, path);
BufferedWriter path_writer = new BufferedWriter(new FileWriter(path_file));
if(!path_file.exists()){
path_writer.write(path);
}
}
}
So what is the problem you are actually having?
A comment:
file_chooser.setCurrentDirectory(new java.io.File("user.home"));
This won't set the current directory to be the users home directory. But to a directory (if it exists) named "user.home" in the current directory. What you probably wanted to do is:
file_chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home")));
Update By reading your comment on this answer:
You already have an absolute path in your variable path. But using the constructor new File(user_home_folder, path) your prefixing it with the location of the user's home directory. This results in a path like that has for example the drive letter twice in it. Remove the first parameter of this constructor.

Inputting a text file into a program?

I had a lecture today on inputting and outputting but it didn't really seem to explain where the text file is etc..
here is my code:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I get a file not found exception but the text file is in the same folder as the program?
Please first read up on the difference between relative and absolute paths. An absolute path is:
C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\lab1task3.txt
A relative path would be just "lab1task3.txt", which is what is given. That means that lab1task3.txt can be found relative to the working directory (e.g if the working directory was "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" then it would find it).
However, you could also use an absolute path, but remember that doing so means that it will only work if a file is in the same place on the machine running it. E.g, if you submit with "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" in your code then it will only work if someone else has that same file and location on their computer. Please note that if this is an assignment, the module convenor/marker probably does not have afolder called C:\Users\Ceri.... If you submit your work using a relative path, anyone using your code just needs to make sure the file is relatively in the same place (e.g in the same folder).
If this doesn't matter, you need to escape the back slash characters with another back slash in the path. This should work:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I notice you are using eclipse. Your "working directory" is your workspace. Therefore you want to move your file to:
C:\Users\Ceri\workspace1\inputoutput\lab1task3.txt
This should work for you using a "relative" path which you had in your opening post.
You're confusing class file location and the "user's working directory", the latter being what Java uses to determine the root of the file path (unless absolute paths are needed), and you can find its location easily via:
System.out.println(System.getProperty("user.dir"));
I advise you to forgo use of files altogether when all you need to do is read in data, and instead get the text file as a program resource:
// where you swap the name of your class for MyClass
InputStream fileResource = MyClass.class.getResourceAsStream("myFile.txt");
Scanner scanner = new Scanner(inputStream);
Note that if you must use a File, then find out what the user's working directory is, as shown above, and then tailor your file path so that it is relative to this working directory.
Try:
File file = new File("src/inputoutput/lab1task3.txt");
My guess is that your current working directory is not the same place as the project location. If your working directory were, the file would definitely be found if it does indeed have that name.
To workaround this issue you can always be using a InputStream instead, like so:
InputStream inputStream = new InputStream("lab1task3.txt");
Scanner scanner = new Scanner(inputStream);
If you want to see your current working directory you can use something like this:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}

How to remove garbage value from a file name which has been created by using createTempFile() method

I have used File.createTempFile() method to create temp file but as its output it appends the garbage value with the file name too. I used the method for uploading zipfile, but unable to delete those appended garbage value. For further functionality I need the exact name of file.
Kindly help...
Highly appreciate your response.
My concern is, as code stated by niiraj874u, I am getting the the File name : tmp4501156806082176909.txt
But I want only tmp.txt How can I remove appended numeric value?
You can use java.io.File.getName() method to get name of file..
import java.io.File;
import java.io.IOException;
public class FileDemo {
public static void main(String[] args) {
File f = null;
// creates temporary file
try {
f = File.createTempFile("tmp", ".txt", new File("D:/"));
} catch (IOException e) {
e.printStackTrace();
}
// prints name of temp file
System.out.println("File name: "+f.getName());
// prints absolute path
System.out.println("File path: "+f.getAbsolutePath());
}
}
this will print like
File name: tmp4501156806082176909.txt
File path: D:\tmp4501156806082176909.txt
It sounds like you don't need a temp file. The purpose of the "garbage" is to protect two or more instances of the app from overwriting each other. In this case use system.getProperty("java.io.temp") to get the temp dir.

Categories

Resources