本篇文章为大家展示了怎样读取本地二进制文件到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字符串中,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注天达云行业资讯频道。