[英]how to create dynamic paths in java and write the file data in java
I will get dynamic paths from database. 我将从数据库获取动态路径。 Example: 1.xyz/abc/file1.txt 2.pqr/file2.txt
示例:1.xyz/abc/file1.txt 2.pqr / file2.txt
Now I need to append these paths to existing file (eg:/users/rama/) and save that file 现在,我需要将这些路径附加到现有文件(例如:/ users / rama /)并保存该文件
my final directory should like /users/rama/xyz/abc/file1.txt 我的最终目录应该是/users/rama/xyz/abc/file1.txt
I am able to create directories such as xyz/abc if they don't exist, but the problem is file1.txt is also created as directory instead of file. 我可以创建xyz / abc之类的目录(如果不存在),但是问题是file1.txt也被创建为目录而不是文件。
I am able to create directories such as xyz/abc if they don't exist, but the problem is file1.txt is also created as directory instead of file.
我可以创建xyz / abc之类的目录(如果不存在),但是问题是file1.txt也被创建为目录而不是文件。
Because you are creating the directories until *.txt. 因为您正在创建目录,直到* .txt。 Below an example of code to acheive what you want:
下面是实现所需内容的代码示例:
String prefix = "/users/rama/";
String filePath = "xyz/abc/file1.txt";
// concatenation => /users/rama/xyz/abc/file1.txt
String fullPath = prefix.concat(filePath);
PrintWriter writer;
try {
// Getting the directory path : /users/rama/xyz/abc/
int lastIndexOfSlash = fullPath.lastIndexOf("/");
String path = filePath.substring(0, lastIndexOfSlash);
File file = new File(path);
// If /users/rama/xyz/abc/ don't exist then creating it.
if(!file.exists()) {
file.mkdirs();
}
// Creating the file.
writer = new PrintWriter(fullPath, "UTF-8");
writer.println("content");
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.