如何更改 java.io.File 对象中的文件路径位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20395592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:38:05  来源:igfitidea点击:

How to change file path location in java.io.File object

javafile-io

提问by Arunkumar

The question says it all. I have a File object which is pointing to /home/user/filename1.

问题说明了一切。我有一个指向/home/user/filename1.

If I call file.getAbsolutePath() then it would return /home/user/filename1

如果我调用 file.getAbsolutePath() 那么它会返回 /home/user/filename1

My question is that -

我的问题是——

  1. Can we change the path inside file object to a different location?
  2. If yes, then how?
  1. 我们可以将文件对象内的路径更改为不同的位置吗?
  2. 如果是,那么如何?

Thanks

谢谢

采纳答案by Blub

"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. "

“File 类的实例是不可变的;也就是说,一旦创建,File 对象表示的抽象路径名就永远不会改变。”

From the File javadoc.

从文件javadoc

回答by Thijser

A file is internally nothing else other then a string holding the path to the file. So no this is not possible. Why would you even want to do something like this? Unless you have moved the file to another location?

一个文件在内部除了一个保存文件路径的字符串之外别无其他。所以不,这是不可能的。为什么你甚至想做这样的事情?除非您已将文件移动到另一个位置?

回答by Jorge_B

As someone noted before, File is immutable as many of java API classes. Maybe what you want is to copy a file from somewhere to some other place? Have in mind that a File object has no actual binding to the contents of the file, and will not allow you modifying or moving it.

正如之前有人指出的,File 与许多 Java API 类一样是不可变的。也许您想要的是将文件从某个地方复制到其他地方?请记住, File 对象没有实际绑定到文件的内容,并且不允许您修改或移动它。

Have a look at Apache Commons IO

看看 Apache Commons IO

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

Here you have a useful library to deal with files.

这里有一个有用的库来处理文件。

回答by Manoj Krishna

I had developed a code to rename the file and I have to save the file in the same location recursively. I think the below code helps you out upto some extent. I have to replace "-a" in my filename and save it in the same folder. If needed in place of "destPath" you can give the destination path of your string path. I think this might help you.

我开发了一个代码来重命名文件,我必须递归地将文件保存在同一位置。我认为下面的代码可以在一定程度上帮助你。我必须替换文件名中的“-a”并将其保存在同一文件夹中。如果需要代替“destPath”,您可以提供字符串路径的目标路径。我想这可能对你有帮助。

File oldfile =new File(file.getAbsolutePath());
    String origPath = file.getCanonicalPath();
    String destPath = origPath.replace(file.getName(),"");
    String destFile = file.getName();
    String n_destFile = destFile.replace("-a", "");
    File newfile =new File(destPath+n_destFile);