java操作字符串生成json文件,自己备份
具体代码如下:
public class CreateFileUtil {
private static Logger log = LoggerFactory.getLogger(TaskService.class);
/**
* 生成.json格式文件
*/
public static boolean createJsonFile(String jsonString, String filePath, String fileName) throws Exception {
// 标记文件生成是否成功
boolean flag = true;//fileName =new String(fileName.getBytes(), "UTF-8" );
//fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
//fileName = new String(fileName.getBytes("iso-8859-1"),"gbk");
// fileName = URLEncoder.encode(fileName,"UTF-8");
// fileName = URLCodec.encodeUrl(fileName,"UTF-8");//fileName = URLEncoder.encode(fileName,"UTF-8");
//fileName = URLDecoder.decode(fileName);
log.info("zip文件里面的名称:"+fileName);
// 拼接文件完整路径
String fullPath = filePath + File.separator + fileName + ".json"; //可修改为 xml 等格式
// 生成json格式文件
try {
// 保证创建一个新文件
File file = new File(fullPath);
if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
file.getParentFile().mkdirs();
}
if (file.exists()) { // 如果已存在,删除旧文件
file.delete();
}
file.createNewFile();if(jsonString.indexOf("'")!=-1){
//将单引号转义一下,因为JSON串中的字符串类型可以单引号引起来的
jsonString = jsonString.replaceAll("'", "\\'");
}
if(jsonString.indexOf("\"")!=-1){
//将双引号转义一下,因为JSON串中的字符串类型可以单引号引起来的
jsonString = jsonString.replaceAll("\"", "\\\"");
}if(jsonString.indexOf("\r\n")!=-1){
//将回车换行转换一下,因为JSON串中字符串不能出现显式的回车换行
jsonString = jsonString.replaceAll("\r\n", "\\u000d\\u000a");
}
if(jsonString.indexOf("\n")!=-1){
//将换行转换一下,因为JSON串中字符串不能出现显式的换行
jsonString = jsonString.replaceAll("\n", "\\u000a");
}// 格式化json字符串
jsonString = JsonFormatTool.formatJson(jsonString); //导出的数据显示json串 没有这行代码则显示字符串// 将格式化后的字符串写入文件
Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
write.write(jsonString);
write.flush();
write.close();
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
// 返回是否成功的标记
return flag;
}
public static void main(String[] args) throws Exception {
String fileName = "你好啊";
try {
//fileName=new String(fileName.getBytes(),"UTF-8");
fileName = URLEncoder.encode(fileName,"UTF-8");
// System.out.print(fileName);
String decode = "1.1%E7%AE%A1%E7%90%86%E5%91%98%E5%88%9B%E5%BB%BA%E8%BF%90%E8%90%A5%E7%AE%A1%E7%90%86%E4%BA%BA%E5%91%98%E8%B4%A6%E5%8F%B7.txt";
decode = URLDecoder.decode(decode);
System.out.print(decode);createJsonFile("nihsss","D:/testjcz",decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}