将博客的文章根据userId保存到本地,使用随机数+日期来生成随机文件名
package com.version2.blog.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* Created by Skye on 2018/6/15.
*/
public class PathUtil {
//将博客内容存放到D:\Java\blogArticals下面去,然后对于每个用户,都有一个具体的文件夹,
// 存放的根路径
public static String getBlogBasePath(){
String blogBasePath = "D:\\Java\\blogArticals\\";
return blogBasePath;
}
//根据用户userId返回博客的根路径
public static String getBlogRelativePath(Integer userId){
String blogRelativePath = "user\\" + userId + "\\blogs\\";
return blogRelativePath;
}
//生成唯一的随机博客名 时间格式与随机数
private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
private static final Random random = new Random();
//保存在classpath下的路径
private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
/**
*生成随机博客名。当前日期 + 五位随机数
* @return
*/
private static String getRandomFileName(){
int randomNum = random.nextInt(89999) + 10000;
String nowTimeStr = simpleDateFormat.format(new Date());
return nowTimeStr + randomNum;
}
/**
* 传入相对路径
* 创建目标路径上所涉及到的路径:如user\blogs\1\
* 若其中的picture,等文件夹不存在,则创建出来
* @param
*/
private static void makeDirPath(String relativePath){
//博客应该存储的绝对路径
String realFileParentPath = getBlogBasePath() + relativePath;
File dirPath = new File(realFileParentPath);
if(!dirPath.exists()){
dirPath.mkdirs();
}
}
/**
* 根据用户Id 获取相对路径,并且将文章保存到路径下,返回相对路径
* @param artical
* @param userId
* @return
*/
public static String saveArticalToDir(String artical, Integer userId){
//获取随机的博客名
String randomFileName = getRandomFileName();
//获取相对路径
String blogRelativePath = getBlogRelativePath(userId);
//创建相对应的文件夹
makeDirPath(blogRelativePath);
blogRelativePath += randomFileName + ".html";
//获取绝对路径
String articalPath = getBlogBasePath() + blogRelativePath;
//File file = new File(articalPath);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(articalPath, false);
byte[] bytes = artical.getBytes();
fileOutputStream.write(bytes, 0, bytes.length);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return blogRelativePath;
}
}