简单的两个写文件的方法

/**
	 * 读取指定的文件,并返回文件的内容
	 * @param filePath 文件的全路径:ftp://home/xml/a.xml
	 * @return 读取到的文件内容,若读取出现问题则返回 ""
	 */
	private String readFile(String filePath){
		String content = "";
		//下载文件到本地
		try {
			logger.info("download file:"+filePath+"---to "+locaPath);
			File file = FtpTool.getFile(filePath,locaPath);
			FileInputStream fin = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			int a ;
			while ((a=fin.read(bytes)) != -1) {
				content += new String(bytes,0,a,"utf-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}
	
	/**
	 * 根据传入的路径:ftp://portal:portal@host/path/filename.xml
	 * 返回文件名称:filename.xml
	 * @param filePath
	 * @return
	 */
	private String getFileName(String filePath){
		return filePath.substring(filePath.lastIndexOf("/")+1);
	}
	
	/**
	 * 往指定的地址写文件
	 * @param content 须要写入文件的内容
	 * @param path 文件的全路径包含文件名
	 * @return 返回成功 or 失败
	 */
	public static boolean saveFile(String content ,String path){
		try {
			File file_out = new File(path);
                           if(!file_out.exists()){
                              File filepath = new File(path.substring(0,path.lastIndexOf("/")));
                              if(!filepath.exists()){
                                 filepath.mkdirs();
                                }
                            file_out.createNewFile();
                            }
FileOutputStream os= new FileOutputStream(file_out);
			os.write(content.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}		
		return true;
	}
相关文章
相关标签/搜索