使用FileInputStream不能读取文本文件的测试
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 测试FileInputStream和FileOutputStream的使用
*
* 结论:
* 1.对于文本文件(.txt, .java, .c, .cpp),使用字符流处理
* 2.对于非文本文件(.jpg, .mp3, .mp4, .avi, .doc, .ppt, ...),使用字节流处理
*/
public class FileInputOutputStreamTest {
//使用字节流FileInputStream处理文本文件,可能出现录入失败的情况。
// (假如输入到控制台显示,会出现翻译失败的情况,例如:*中*。
//但是如果在运输过程中,不去查看,那复制的中文就不会出现翻译失败的情况。
@Test
public void testFileInputStream(){
FileInputStream fis = null;
try {
//1.造文件
File file = new File("hello.txt");
//2.造流
fis = new FileInputStream(file);
//3.读数据
byte[] buffer = new byte[5];
int len;//记录每次读取的字节的个数
while ((len = fis.read(buffer)) != -1){
String str = new String(buffer, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步