工具類 讀取本地二進位制檔案到String字串中
阿新 • • 發佈:2019-07-29
注意:本工具類就是隻能讀取本地的<二進位制>檔案。
import java.io.*;
/**
* 檔案操作工具類
*
* @author edison_kwok
*/
public class FileUtils {
/**
* 本地檔案重新命名
*
* @param file
* @param newName
*/
public static void rename(File file, String newName) {
if (file.exists()) {
String absolutePath = file.getAbsolutePath();
String path = absolutePath.substring(0, absolutePath.lastIndexOf("\\") + 1);
file.renameTo(new File(path + newName));
}
}
/**
* 功能:Java讀取txt檔案的內容
* 步驟:1:先獲得檔案控制代碼
* 2:獲得檔案控制代碼當做是輸入一個位元組碼流,需要對這個輸入流進行讀取
* 3:讀取到輸入流後,需要讀取生成位元組流
* 4:一行一行的輸出。readline()。
* 備註:需要考慮的是異常情況
*
* @param filePath
*/
public static String readFile(String filePath) {
InputStreamReader read = null;
BufferedReader bufferedReader = null;
String lineTxt = null;
try {
String encoding = "UTF-8";
File file = new File(filePath);
//判斷檔案是否存在
if (file.isFile() && file.exists()) {
//考慮到編碼格式
read = new InputStreamReader(new FileInputStream(file), encoding);
bufferedReader = new BufferedReader(read);
StringBuilder stringBuilder = new StringBuilder();
while ((lineTxt = bufferedReader.readLine()) != null) {
stringBuilder.append(lineTxt);
}
return stringBuilder.toString();
} else {
throw new RuntimeException("該檔案不存在");
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (read != null) {
read.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 輸出流匯出本地檔案
*
* @param is
* @param os
* @throws Exception
*/
public static void fileUpload(InputStream is, OutputStream os) throws Exception {
byte[] b = new byte[2048];
int length = 0;
while (true) {
length = is.read(b);
if (length < 0) break;
os.write(b, 0, length);
}
is.close();
os.close(