【文件操作】 將文件內容轉爲String對象 、base64編碼

文件內容:text.txt

{"name":"利威爾","number":"abc123"}

主類:

package practiceDemo1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;


public class TestFile01 {
	public static void main(String[] args) {
		String fileContent = encodeBase64File("E://text.txt");
		System.out.println("base64編碼:");
		System.out.println(fileContent);
		
		byte[] buffer = new byte[(int) fileContent.length()];
		String str = "";
		try {
		buffer = Base64.getDecoder().decode(fileContent);  //base64編碼轉爲byte[]
		str = new String(buffer,"gb2312");  //byte[]轉爲String
		}catch(Exception e) {

		}
		System.out.println("文件原內容:");
		System.out.println(str);
	}
	
	//讀取文件,將文件內容轉爲base64編碼
	public static String encodeBase64File(String path) {
		File file = new File(path);
		FileInputStream inputFile;
		byte[] buffer = null;

		try {
			inputFile = new FileInputStream(file);
			buffer = new byte[(int) file.length()];
			inputFile.read(buffer);
			inputFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return Base64.getEncoder().encodeToString(buffer);

	}
	
}

運行結果:

base64編碼:
eyJuYW1lIjoiwPvN/rb7IiwibnVtYmVyIjoiYWJjMTIzIn0=
文件原內容:
{"name":"利威爾","number":"abc123"}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章