在使用unicloud云数据库时,大量数据导入需要json格式,所以用java写了一个简单的生成json文件代码,可以直接导入云数据库,代码不固定,可以根据自己需要二次改写
以下是代码
import java.io.*;
import java.util.*;
public class exchange {
public static int len = 0;
public static void main(String[] args) throws IOException {
File f = new File("目录"); //pathname为保存稿件文件的文件夹路径
List<String> title = getFileName(f);
System.out.println(title);
BufferedWriter bw = new BufferedWriter(new FileWriter("json格式文件名"));
for (String ls : title) {
bw.write(ls);
bw.newLine();
bw.flush();
}
bw.close();
}
public static List<String> getFileName(File f) throws IOException { //f为保存稿件文件的文件夹路径
List<String> list = new ArrayList<String>();
File[] files = f.listFiles();
for (File file:files){
int len = file.getName().split("\\.").length;
if (len>1){
String name = file.getName().split("\\.")[0];
System.out.println(name);
String path = file.getAbsolutePath();
System.out.println(path);
List<Object> content = getFileContent(path);
list.add("{"+"\"title\""+":"+"\""+name+"\""+",");
list.add("\"file-tag\"" + ":" + "\"标签名\"" + ","); //文章标签替换为文章分类名字就好
for (Object o : content) {
String o1 = (String) o;
list.add("\"content\""+":"+ "\""+o1.replace("\r\n", "<br/>").replace("\"","'").replace("\\","").replace(" ","_")+"\""+"}");
}
}
}
return list;
}
public static List<Object> getFileContent(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
List<Object> list = new ArrayList<Object>();
char[] chs = new char[1024*100];
while ((len=br.read(chs))!=-1) {
list.add(new String(chs, 0, len));
}
br.close();
return list;
}
}
效果