是否可以在不创建新实例的情况下更改java中File类的文件路径?
File file = new File(System.getProperty("user.home")); <br>
System.out.println(file.getPath());
返回C:\Users\用户名
现在我想转到父目录。我想我可以使用这样的东西
file.setPath(file.getParent());
但我必须使用
file = new File(file.getParent());
还有什么其他方法可以达到同样的效果吗?或者也许我可以创建多个实例,将它们存储在数组中并同时使用两个对象(目录)?
最佳答案
来自the javadocs :
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
所以,不,您不能更改 File 实例。如果您想要不同的值,则必须实例化一个新文件。
关于java - java中的新文件路径,没有新的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960165/