java 將本地文件或網絡文件與base64互相轉換


一:將網絡文件轉為Base64

將文件轉為base64

public static String fileToBase64(String url){
	int byteread = 0;
	String total = null;
	byte[] totalbyte = new byte[0];
	try {
		URL url = new URL(url);
		URLConnection conn = url.openConnection();
		InputStream inStream = conn.getInputStream();
		byte[] buffer = new byte[1204];
		while ((byteread = inStream.read(buffer)) != -1) {
			//拼接流,這樣寫是保證文件不會被篡改
			totalbyte = byteMerger(totalbyte,buffer,byteread);
		}
		inStream.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return Base64.encodeBase64String(totalbyte)
}

  將base轉為文件

  

public static void base64ToFile(String base64, String filePath) {
		try {
			byte[] bytes = Base64.decodeBase64(base64);
			//base解密
			File videoFile = new File(filePath);
			//輸入文件
			FileOutputStream fos = new FileOutputStream(videoFile);
			fos.write(bytes, 0, bytes.length);
			fos.flush();
			fos.close();
		} catch (IOException e) {
		}
	}

  

二:將本地文件轉Base64

轉Base64

public static String videoToBase64(File videofilePath) {
		long size = videofilePath.length();
		byte[] imageByte = new byte[(int) size];
		FileInputStream fs = null;
		BufferedInputStream bis = null;
		try {
			fs = new FileInputStream(videofilePath);
			bis = new BufferedInputStream(fs);
			bis.read(imageByte);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Base64.encodeBase64String(imageByte);
	}

  

將Base64轉文件

public static void base64ToFile(String base64, String filePath) {
		try {
			byte[] bytes = Base64.decodeBase64(base64);
			//base解密
			File videoFile = new File(filePath);
			//輸入文件
			FileOutputStream fos = new FileOutputStream(videoFile);
			fos.write(bytes, 0, bytes.length);
			fos.flush();
			fos.close();
		} catch (IOException e) {
		}
	}

  

注意:

在將文件轉Base64字符時,如果使用sun下的BASE64Encoder時會導致轉換出來的Base64自動換行,原因是RFC2045中有規定Base64一行不能超過76字符,超過則添加回車換行符所以導致轉換出來的Base64字符會出現換行,解決方法是使用Apache的 commons-codec.jar,Base64.encodeBase64String(byte[])得到的Base64字符不會出現換行

commons-codec   1.4版本時也會出現換行,使用1.8時不會出現換行,其他版本沒有測試

 

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.8</version>
</dependency>

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM