从磁盘中读取文件内容以及从内存中将数据写入磁盘中

public  BaseResult testReadFile() {
		
		String fileContent = "";
		try {

		File f = new File("E:\\新建文本文档.txt");

		if(f.isFile()&&f.exists()) {
			InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");
			
			BufferedReader reader=new BufferedReader(read);
	
			String line;
	
			while ((line = reader.readLine()) != null) {
	
			fileContent += line;
		
			}
			Map map = JsonMapper.defaultMapper().fromJson(fileContent, Map.class);
			Object department = map.get("department");
			String medStr = JsonMapper.defaultMapper().toJson(department);
			String s = medStr.substring(1, medStr.length()-1);
			System.out.println(s);
			read.close();
		}
		} catch (Exception e) {
			System.out.println("读取文件内容操作出错");

			e.printStackTrace();
		}
		return BaseResult.ok();
	}
  public void testWriteFile(){
	  String data = "字段名为小写\r\n" + 
				"字段名为有意义的单词,或单词的缩写\r\n" + 
				"如果字段由几个单词组成,则单词间用下划线(“_”)分割,如client_id,post_code等\r\n" + 
				"字段名限制在30个字符内。当字段名超过30字符时,可用缩写来减少字段名的长度,如description –>"
				+ " desc;information –> info;address –> addr等";
		
		byte[] sourceByte = data.getBytes();
	    String path = "D:/file/";
	    String fileName = "test.txt";
	    
	    if(null != sourceByte){
	        try {
	        	//文件路径(路径+文件名)
	            File file = new File(path+fileName);
	          //文件不存在则创建文件,先创建目录
	            if (!file.exists()) {   
	                File dir = new File(file.getParent());
	                dir.mkdirs();
	                file.createNewFile();
	            }
	            //文件输出流将数据写入文件
	            FileOutputStream outStream = new FileOutputStream(file);
	            outStream.write(sourceByte);
	            outStream.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	            // do something
	        } finally {
	            // do something
	        }
	    }
	}
	  

 

你可能感兴趣的:(Java基础)