方法摘要
Modifier and TypeMethod and Descriptionintavailable()返回从此输入流中可以读取(或跳过)的剩余字节数的估计值,而不会被下一次调用此输入流的方法阻塞。voidclose()关闭此文件输入流并释放与流相关联的任何系统资源。protected voidfinalize()确保当这个文件输入流的 close方法没有更多的引用时被调用。FileChannelgetChannel()返回与此文件输入流相关联的唯一的FileChannel对象。FileDescriptorgetFD()返回表示与此 FileInputStream正在使用的文件系统中实际文件的连接的 FileDescriptor对象。intread()从该输入流读取一个字节的数据。intread(byte[] b)从该输入流读取最多 b.length个字节的数据为字节数组。intread(byte[] b, int off, int len)从该输入流读取最多 len字节的数据为字节数组。longskip(long n)跳过并从输入流中丢弃 n字节的数据。
代码演示:
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author
* @version 1.0
*/
public class FileInputStream_ {
public static void main(String[] args) {
}
/**
* 演示读取文件
* read(byte b)单个字节的读取,效率较低
* 使用 read(byte[] b) 来读取
*/
@Test
public void readFile01(){
String filePath = "e:\\hello.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止
//如果返回-1.表示读取完毕
while((readData = fileInputStream.read()) != -1){
System.out.print((char)readData);//转成char显示
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void readFile02(){
String filePath = "e:\\hello.txt";
byte[] buf = new byte[8];//一次读8个字节
int readLen = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取文件
fileInputStream = new FileInputStream(filePath);
// 读取的字节数最多等于b的长度。
// 令k为实际读取的字节数; 这些字节将存储在元素b[0]至b[ k -1] ,使元素b[ k ]至b[b.length-1]不受影响。
方法摘要
Modifier and TypeMethod and Descriptionvoidclose()关闭此文件输出流并释放与此流相关联的任何系统资源。protected voidfinalize()清理与文件的连接,并确保当没有更多的引用此流时,将调用此文件输出流的 close方法。FileChannelgetChannel()返回与此文件输出流相关联的唯一的FileChannel对象。FileDescriptorgetFD()返回与此流相关联的文件描述符。voidwrite(byte[] b)将 b.length个字节从指定的字节数组写入此文件输出流。voidwrite(byte[] b, int off, int len)将 len字节从位于偏移量 off的指定字节数组写入此文件输出流。voidwrite(int b)将指定的字节写入此文件输出流。
代码演示:
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author
* @version 1.0
*/
public class FileOutputStream_ {
public static void main(String[] args) {
}
@Test
public void writeFile(){
String filePath = "e:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
String str = "Hello World!";
//得到FileOutputStream对象
//1. new FileOutputStream(filePath) 创建方式,写入内容会默认覆盖原来的内容
//2. new FileOutputStream(filePath, append) 创建方式,append 为ture,写入内容会默认追加至原来的内容后,否则就覆盖
fileOutputStream = new FileOutputStream(filePath, true);
//写入一个字节
fileOutputStream.write('H');
//写入字符串,str.getBytes() 可以把 字符串 -》字符数组
fileOutputStream.write(str.getBytes());
/*
write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off的指定字节数组写入文件输出流