how to create dynamic paths in java and write the file data in java

时间:2016-07-11 20:43:48

标签: java file-io

I will get dynamic paths from database. Example: 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

my final directory should like /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.

1 个答案:

答案 0 :(得分:0)

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.

Because you are creating the directories until *.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();
}