比如我有一个1.txt,里面内容如下
1.在堆中开辟对象所需空间,分配地址
2.初始化对象
3.将内存地址返回给栈中的引用变量
现在,我要读取这个文本。
1.字节流方式
public class IOTest {
String filePath = "c:/1.txt";
@Test
public void dataStream() throws Exception{
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()]; //打算一口气读完
fis.read(bytes); //把字节全部读到数组里面
System.out.println(new String(bytes));
}
}
2.字符流方式
@Test
public void CharStream() throws Exception{
File file = new File(filePath);
FileReader fr = new FileReader(file);
char[] cbuf = new char[(int) file.length()]; //打算一口气读完
fr.read(cbuf);//把字符全部读到数组里面
System.out.println(new String(cbuf));
}
3.缓冲流方式(按行读取)
@Test标签:fr,Java,读取,filePath,File,file,new,手写,String From: https://blog.51cto.com/u_10957019/5809102
public void BufferStream() throws Exception{
File file = new File(filePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
}