递归提取目录下的所有json格式的文件,重命名,并保存到另外的目录

所使用的jar: commons-io-2.4.jar,jackson-annotations-2.8.0-20160405.011944-16.jar,jackson-core-2.8.0-20160403.234143-59.jar,jackson-databind-2.8.0-20160407.052136-77.jar

代码Bean类:

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * 
 * 这个Bean类对应了目录中的很多json文件,将json文件中共有的属性提取出来,形成了这个通用的Bean
 * json文件中含有特殊字符的名称,在java中无法定义为字符串的名称,
 * 通过JsonProperty方式,映射到对应的java字符串,
 * 如"@odata.id",无法声明java字符串为@odata.id,如何将json中的@odata.id赋给Bean类呢
 * 能过JsonProperty方式解决这类问题
 *  @JsonProperty("@odata.id") private String odataId;
 */

/**
 * ObjectMapper类用序列化与反序列化映射器  
 * ObjectMapper mapper = new ObjectMapper();  
 * 
 * 当反序列化json时,未知属性会引起的反序列化被打断,这里我们禁用未知属性打断反序列化功能
 * 因为,例如json里有10个属性,而我们的bean中只定义了2个属性,其它8个属性将被忽略 
 * mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
 */

/**@JsonIgnoreProperties(ignoreUnknown=true)也可以忽略多余的属性
*/
 public class CommonBean {
    
	@JsonProperty("@odata.context") private String odataContext;
    @JsonProperty("@odata.id") private String odataId;
    @JsonProperty("@odata.type") private String odataType;
    @JsonProperty("Id") private String id;
    @JsonProperty("Name") private String name;
    
	public CommonBean() {
		
	}

	public String getOdataContext() {
		return odataContext;
	}

	public void setOdataContext(String odataContext) {
		this.odataContext = odataContext;
	}

	public String getOdataId() {
		return odataId;
	}

	public void setOdataId(String odataId) {
		this.odataId = odataId;
	}

	public String getOdataType() {
		return odataType;
	}

	public void setOdataType(String odataType) {
		this.odataType = odataType;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
    
    
    
}

代码递归目录下的文件,重命名,保存到另外的目录

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/*
 * 递归提取目录下的所有json格式的文件,重命名,并保存到另外的目录
 * 
 */
public class ExtractFilesFromFolder {
	
	private String saveFilePath = "json_data";
	
	private List<String> successfulFileList = new ArrayList<String>();
	
	private List<String> failedFileList = new ArrayList<String>();
	
	private List<String> allFileList = new ArrayList<String>();
	
	
	public ExtractFilesFromFolder(){
		
	}
	
	public ExtractFilesFromFolder(String saveFilePath){
		this.saveFilePath = saveFilePath;
	}
	
	public void FolderRecursion(String filePath){
		File root = new File(filePath);
		File[] files = root.listFiles();
		for( File file : files){
			if(file.isFile()){
				readAndSaveFile(file.getPath());
			}else{
				FolderRecursion(file.getPath());
			}
		}
	}
	
	public void readAndSaveFile(String filePath){
		try {
			allFileList.add(filePath);
	        InputStream inputStream = new FileInputStream(filePath);
	        /*借用第三方工具类,一下子读取文件的所有内容*/
	        String fileContent =  IOUtils.toString(inputStream);
	        inputStream.close();
	        
	        
	        /*ObjectMapper类用序列化与反序列化映射器*/
	        ObjectMapper mapper = new ObjectMapper();
	        /*当反序列化json时,未知属性会引起的反序列化被打断,这里我们禁用未知属性打断反序列化功能,  
                 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            	因为,例如json里有10个属性,而我们的bean中只定义了2个属性,其它8个属性将被忽略 */
			mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 
	        File sourceFile = new File(filePath);
	        /*从json映射到java对象*/
	        CommonBean comBean = mapper.readValue(sourceFile, CommonBean.class);
	        String odataId = comBean.getOdataId();
	        
	        String fileName = odataId.substring(1).replaceAll("/", "_")+".json";
	        String targetFilePath = saveFilePath+"\\"+fileName;
	        File targetFile = new File(targetFilePath);
	        if( targetFile.exists() ){
	        	targetFilePath += "-2";
	        	targetFile = new File(targetFilePath);
	        }
	        	targetFile.createNewFile();
	        
	        FileOutputStream fos = new FileOutputStream(targetFile);
             /* 以UTF-8格式 保存文件  */  
              OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); 
	        
	        osw.write(fileContent,0,fileContent.length());
	        osw.flush();
	        osw.close();
	        allFileList.add(targetFilePath);
	        successfulFileList.add(targetFilePath);
		}  catch (Exception e) {
			e.printStackTrace();
			failedFileList.add(filePath);
		} 
	}
	

	public void setSaveFilePath(String saveFilePath) {
		this.saveFilePath = saveFilePath;
	}

	public String getSaveFilePath() {
		return saveFilePath;
	}

	public List<String> getSuccessfulFileList() {
		return successfulFileList;
	}

	public List<String> getFailedFileList() {
		return failedFileList;
	}

	public List<String> getAllFileList() {
		return allFileList;
	}
	
	
}

测试类:

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String filePath = "development"; 
		ExtractFilesFromFolder extractFiles = new ExtractFilesFromFolder();
		extractFiles.FolderRecursion(filePath);
		System.out.println("Successful files, number : "+extractFiles.getSuccessfulFileList().size()+","+extractFiles.getSuccessfulFileList());
		System.out.println("==============================================");
		System.out.println("Failed files, number :"+extractFiles.getFailedFileList().size()+","+extractFiles.getFailedFileList());
		System.out.println("==============================================");
		System.out.println("All files, number :"+extractFiles.getAllFileList().size()+","+extractFiles.getAllFileList());
		for(int i=0; i<extractFiles.getAllFileList().size();i++){
			System.out.println(extractFiles.getAllFileList().get(i));
		}
	}

}
filePath = "development" 是工程根目录下的文件夹


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值