我希望能够使用可在文件路径中更改的变量。与文件路径相关的用户名在构造函数中声明,然后我尝试将其分配给下面方法中的文件路径。
致电时我想要发生的事情:
System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));
文件路径是那么:
C:\Users\ryanb\Documents
相反,当我致电documentsPath.toString()
时,我才会回来:
C:\Users\
如何使用String用户名和documentsPath
分配"\\Documents"
变量。
这是我的代码:
class profileCopy{
/*global variables */
private Path documentsPath;
private Path desktopPath;
private Path favoritesPath;
private Path networkFolder;
private String username;
private String foldername;
public profileCopy(String username, String foldername)
{
this.username = username;
this.foldername = foldername;
documentsPath = Paths.get("C:\\Users");
desktopPath = Paths.get("C:\\Users");
favoritesPath = Paths.get("C:\\Users");
networkFolder = (Paths.get("F:\\Data\\WP51"));
}
public void copyDocumentsFolder() throws IOException
{
Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));
System.out.format("%s%n", networkFolder.resolve(foldername + "\\Backup"));
System.out.println(networkFolder.getFileName());
Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
System.out.println(newDir.toString());
}
答案 0 :(得分:1)
为了使代码不起作用的要点是您不会将resolve()方法的返回值重新分配给路径变量,因为该方法会返回一个新对象。
为了构建你的路径,你可以使用这样的东西:
documentsPath = Paths.get(string.format("C:\\Users\\%s\\%s", username, "Documents");
如果要重用某些代码,可以使用文件夹数组并创建它们:
List<Path> paths = new ArrayList();
String[] defaultFolders = {"Documents", "Desktop", "Music"};
foreach (folder : defaultFolders) {
paths.add(Path.get(string.format("C:\\Users\\%s\\%s", username, folder)));
PS:由于你是在java中开发它,你应该考虑使Path的UNIX或Windows兼容,因为UNIX环境不会识别“C:/ Users”路径。 < / p>
答案 1 :(得分:1)
resolve方法返回Path
public void copyDocumentsFolder() throws IOException
{
Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
documentsPath = documentsPath.resolve(username + "\\Documents");
networkFolder = networkFolder.resolve(foldername + "\\Backup");
System.out.format("%s%n", documentsPath);
System.out.format("%s%n", networkFolder);
System.out.println(networkFolder.getFileName());
Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
System.out.println(newDir.toString());
}