Change the name of the deepest directory in a File object - java

I have File object in Java which is a directory path:
C:\foo\foo\bar
...and I would like to change this to:
C:\foo\foo\newname
I'm don't mean renaming the actual directory, but, simply modifying the path in the File object. Could someone show me how I can do this? Do I have to use string functions for this or is there some inbuilt Java function that I can use?
Thanks.

You can construct one File from another and get the parent directory of a file, combining these:
File orig = new File("C:\\foo\\foo\\bar");
File other = new File(orig.getParentFile(), "newname");

There is no such method in java that changes path for the File object, however you can get the file path with getPath() or getAbsolutePath(). I think creating a new file at that path would do.

Try following:
import java.io.File;
public class MainClass {
public static void main(String[] a) {
File file = new File("c:\\foo\\foo\\bar");
file.renameTo(new File("c:\\foo\\foo\\newname"));
}
}
Hope this helps.

You can use the string-representation of the File object and search for the last / with indexOf(), then you change the value after it and create a new File object.

I guess you need to something like this.
String sourcePath = "C:\\foo\\foo\\bar";
String newName = "newname";
File source = new File(sourcePath);
File dest = new File(source.getParent() + File.separator + newName);
source.renameTo(dest);

I think you can only create a new File object with the new path:
File f2 = new File("C:\\foo\\foo\\newname")
Does it make any side effect on your code?

Related

get path of a file in java

My problem is very simple and yet I can't figure out how to solve it.
I have text files in a folder:
"C:/aaa/bbb/ccc/ddd/test.txt"
And excel files in a folder within the text files folder:
"C:/aaa/bbb/ccc/ddd/excelFiles/test.xls"
Both text and excel files have the same name.
I would like to be able to access the path of those excel files.
What I did is:
this.file.getParent()+"\\"+"excelFiles"+"\\"+file.getName().substring(0, fileName.indexOf('.'))+".xls"
I get a "String index out of range" error.
Thank you for your help :)
If I understand your question, one option is to use File.getCanonicalPath() like,
try {
File f = new File("C:/aaa/bbb/ccc/ddd/excelFiles/test.xls");
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
You might want to try this ->
String dynamicExcelFileName = file.getName().substring(0, fileName.indexOf('.'))
into a variable and use it in the path for accessing the excel file.
this way you get to be extra sure to check if the path is properly captured in variable or not and thus less chances of getting index out of range error.
plus the code is more readable
Looking at your snippet, I can see that you're accessing the file's name in two different ways:
file.getName().substring(...)
and
fileName.indexOf(...).
Are you sure that fileName is not empty when you try to determine the index of the dot?
this.file.getParent()+"\"+"excelFiles"+"\"+file.getName().substring(0, this.file.getName().indexOf('.'))+".xls"
This could be achieved quite easily, even without using existing libraries like FileUtils.
These three method can create the corresponding Excel File object for your text object
private File getExcelFile(final File txtFile) throws IOException {
final String path = txtFile.getCanonicalPath();
final String directory = path.substring(0, path.lastIndexOf(System.getProperty("file.separator")));
return new File(getExcelSubdirectory(directory), getExcelFilename(txtFile.getName()));
}
private File getExcelSubdirectory(final String parent) {
return new File(parent, "excelFiles");
}
private static String getExcelFilename(final String filename) {
return filename.substring(0, filename.lastIndexOf('.')) + ".xls";
}
If you use them like this:
File txt = new File("C:/aaa/bbb/ccc/ddd/test.txt");
System.out.println(txt.getCanonicalPath());
File excel = getExcelFile(txt);
System.out.println(excel.getCanonicalPath());
.. it will print:
C:\aaa\bbb\ccc\ddd\test.txt
C:\aaa\bbb\ccc\ddd\excelFiles\test.xls

How to get the file location using the file path?

In Eclipse, when I right click on the file I want to input from in my project, it shows two things:
path: /SWT/src/data.txt
location: C:\Users\Yoshikawa\workspace\SWT\src\data.txt
Is there any way I can get the location (C:\Users\Yoshikawa\workspace\SWT\src\data.txt) is I know just the path (/SWT/src/data.txt) ?
Ex.
public String ReadFile(String file_path) {
//Search current project directory
return file_location
}
public String readFile(String file_path){
File f = new File(file_path);
return f.getAbsolutePath();
}
You attempt to create a File object based on the file_path and then run the method getAbsolutePath() method of the File class.
h
You can read up more on this here: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Hopefully this works.
Take a look at the Java Path Class.
You can use File.getAbsolutePath or File.getCanonicalPath. They are not the same, see the difference
String relativePath = "../1.txt";
System.out.println(new File(relativePath).getCanonicalPath());
System.out.println(new File(relativePath).getAbsolutePath());
output
D:\workspace1\1.txt
D:\workspace1\x\..\1.txt
see java.io.File API for details

Where to put a file to read from a class under a package in java?

I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}

Can I compose two file paths without needing their toString() methods?

Imagine I have a 'base' path object, denoting a directory, and a 'relative' path object denoting some file within the base.
I would expect that code to look somewhat like
AbsolutePath base = new AbsolutePath("/tmp/adirectory");
RelativePath relativeFilePath = new RelativePath("filex.txt");
AbsolutePath absoluteFile = base.append( relativeFilePath );
But in the Java API (which I don't yet know very well) I find only File, with which I can do nothing better than
File base = new File("/tmp/adirectory");
File relativeFilePath = new File("filex.txt");
File absoluteFile = base.toString()
+ File.separator
+ relativeFilePath.toString();
Is there a better way?
The closest you can get with java.io.File is the File(File, String) constructor:
File base = ...;
File relative = ...;
File combined = new File(base, relative.toString());
If you can use the Path class introduced in Java 7, then you can use the resolve() method, which does exactly what you want:
Path base = ...;
Path relative = ...;
Path combined = base.resolve(relative);
Please note that if base is not an absolute path, then combined won't be absolute either! If you need an absolute path, then for a File you'd use getAbsoluteFile() and for a Path you'd use toAbsoutePath().
Yes. new File(base, "filex.txt") will create a file names "filex.txt" in the directory base.
There is no need to create a relativeFilePath File instance with just the relative name if what you want to do is make it relative to another directory than the current one.
how about:
File base = new File("/tmp/adirectory");
File absoluteFile = new File(base, "filex.txt");
EDIT: Too late #JB Nizet pipped me at the post...
The File class has some constructors which may be of interest to you:
File base = new File("/tmp/adirectory");
File absolute = new File(base, "filex.txt");
File absolute2 = new File("/tmp/adirectory", "filex.txt");

set directory to a path in a file

I just want to set the directory to a path I have written in a file before.
Therefore I used :
fileChooser.setCurrentDirectory(new File("path.txt"));
and in path.txt the path is given. But unfortunately this does not work out and I wonder why :P.
I think I got it all wrong with the setCurrentDic..
setCurrentDirectory takes a file representing a directory as parameter. Not a text file where a path is written.
To do what you want, you have to read the file "path.txt", create a File object with the contents that you just read, and pass this file to setCurrentDirectory :
String pathWrittenInTextFile = readFileAsString(new File("path.txt"));
File theDirectory = new File(pathWrittenInTextFile);
fileChooser.setCurrentDirectory(theDirectory);
You have to read the contents of path.txt. Thea easiest way is through commons-io:
String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File dir = new File(fileContents);
You can also use FileUtils.readFileToString(..)
JFileChooser chooser = new JFileChooser();
try {
// Create a File object containing the canonical path of the
// desired directory
File f = new File(new File(".").getCanonicalPath());
// Set the current directory
chooser.setCurrentDirectory(f);
} catch (IOException e) {
}

Categories