本篇文章為大家展示了怎樣讀取本地二進制文件到String字符串中,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
注意:本工具類就是只能讀取本地的<二進制>文件。
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();
}
}上述內容就是怎樣讀取本地二進制文件到String字符串中,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。