1. 程式人生 > >JAVA檔案工具類之——檔案寫入(byte陣列、String方式、url寫入方式)

JAVA檔案工具類之——檔案寫入(byte陣列、String方式、url寫入方式)

       /**
	 * 將byte陣列寫入檔案
	 * 
	 * @param path
	 * @param fileName
	 * @param content
	 * @throws IOException
	 */
	public static void writeFile(String path, String fileName, byte[] content)
			throws IOException {
		try {
			File f = new File(path);
			if (!f.exists()) {
				f.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(path + fileName);
			fos.write(content);
			fos.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}



	/**
	 * 寫檔案方法
	 * 
	 * @param path
	 * @param name
	 * @param content
	 * @param encoding
	 */
	public static void writeFile(String path, String name, String content,
			String encoding) {
		if (content == null)
			content = "";
		try {
			File f = new File(path);
			if (!f.exists()) {
				f.mkdirs();
			}
                        //利用org.apache.commons.io.FileUtils快速寫檔案
 org.apache.commons.io.FileUtils.writeStringToFile(new File(path + name), content, encoding); } catch (IOException e) { throw new RuntimeException(e); } } /** * 寫檔案 * * @param url * @param dist * @return */ public static boolean writeFile(String url, File dist) { try { writeFile(new URL(url).openStream(), dist); return true; } catch (IOException e) { //無法下載圖片,文字等 } return false; }