如何根据登录参数和日期时间戳生成包含目录和文件名的目录结构?

时间:2015-11-12 20:19:55

标签: java

我有一个方法,它接受hostNameuserName等参数。 我通过添加最近的时间来创建一个fileName。 我想在系统中创建一个文件,其中包含格式/hostName/userName/fileName,以便登录的用户使用自己的凭据在自己的目录中创建文件,用户目录包含其域和用户名。目录/hostName/userName内是一个名为fileName的文件。 EG:

User1: /windows/user1/201512110309.txt

User2: /ubuntu/user2/201512111210.txt

   public File getDirectoryAndFileName(String hostName, String userName) {
                    String fileName = new SimpleDateFormat("yyyyMMddhhmm'.txt'").format(new Date());
                    File file = new File(hostName + userName + fileName);
                    return file;
    }

2 个答案:

答案 0 :(得分:0)

您可以这样做:

public File createFileStructure(hostName, userName) {
  File baseUserDirectory = new File(hostName, userName);
  String userFileNameToBeCreated = "yyyyMMddHHmm.txt";
   if(!baseUserDirectory.exists()) {
     if(!baseUserDirectory.mkdirs()) {
         throw new IllegalStateException("The base user directory does not exist and could not be created: "
                   + baseUserDirectory);
       }
   }
   if(baseUserDirectory.isDirectory ()) {
     throw new IllegalStateException("The base user directory is not a directory: " + baseUserDirectory);
   }
   //till here you will be sure that your user Directory exists.
   return new File(baseUserDirectory, userFileNameToBeCreated);
  }

您只需要以您想要的格式获取日期即可。

答案 1 :(得分:0)

谢谢@recursingMe。我用以下方式实现。

public static void getFile(String hostName, String userName) throws IOException {
            hostName = "/" + hostName;
            userName = "/" + userName;
            File baseUserDirectory = new File(hostName, userName);
            baseUserDirectory.mkdirs();
            String fileName = new SimpleDateFormat("yyyyMMddhhmm'.txt'").format(new Date());        
            File file = new File(baseUserDirectory, fileName);
            file.createNewFile();
        }