输入流【InputStream】
说明:输入流指的是读取数据的操作(以内存为参考)。
构造方法:
FileInputStream(File file):
通过打开一个到实际文件的连接来创建一个
FileInputStream
,该文件通过文件系统中的File
对象file
指定。
FileInputStream(FileDescriptor fdObj):
通过使用文件描述符
fdObj
创建一个FileInputStream
,该文件描述符表示到文件系统中某个实际文件的现有连接。(此方法一般不用)
FileInputStream(String name):
通过打开一个到实际文件的连接来创建一个
FileInputStream
,该文件通过文件系统中的路径名name
指定。
方法摘要:
常用方法:
read():
格式:变量名.read()
未读取到内容时返回-1 。
要读取的文件:
由于此方法一次只能读取一个字节,所以需要用到循环才能完全读取数据
public static void main(String[] args) throws Exception {
File f1 = new File("D:/aa/bb/cc/c.txt");
//创建输入流
InputStream in = new FileInputStream(f1);
//使用循环遍历数据
int n;
while ((n = in.read()) != -1){
System.out.println(n);
}
}
结果:
注意:因为此方法返回的是int类型的数据,所以要还原数据需要对照ascll表。
也可直接转换:
public static void main(String[] args) throws Exception {
File f1 = new File("D:/aa/bb/cc/c.txt");
InputStream in = new FileInputStream(f1);
int n;
while ((n = in.read()) != -1){
System.out.println((char)n);
}
}
read(byte[] b)
格式:变量名.read(byte数组名)
未读取到内容时返回-1 。
public static void main(String[] args) throws Exception {
File f1 = new File("D:/aa/bb/cc/c.txt");
//创建输入流
InputStream in = new FileInputStream(f1);
//创建数组接受数据
byte[] bytes = new byte[10];
//使用循环遍历数据
int n;
while ((n = in.read(bytes)) != -1){
//将数组按照ascll表转换为字符串
String s = new String(bytes,0,n);
System.out.print(s);//由于不能改变数据格式所以此处不要ln
}
}
输出流【OutputStream】
说明:输入流指的是写入数据的操作(以内存为参考)。
构造方法:
FileOutputStream(File file)
创建一个向指定
File
对象表示的文件中写入数据的文件输出流。
FileOutputStream(File file, boolean append)
创建一个向指定
File
对象表示的文件中写入数据的文件输出流。
FileOutputStream(FileDescriptor fdObj)
创建一个向指定文件描述符处写入数据的输出文件流,该文件描述符表示一个到文件系统中的某个实际文件的现有连接。
FileOutputStream(String name)
创建一个向具有指定名称的文件中写入数据的输出文件流。
FileOutputStream(String name, boolean append)
创建一个向具有指定name
的文件中写入数据的输出文件流。
方法摘要:
常用方法:
wite(byte[] b):
public static void main(String[] args) throws Exception {
File f1 = new File("D:/aa/bb/cc/c.txt");
//创建输出流
OutputStream out = new FileOutputStream(f1);
//设置输出内容并转换成byte数组
String str = "qwerty";
byte[] bytes = str.getBytes();
//在指定文件写入内容
out.write(bytes);
//关闭资源
out.close();
}
结果:
综合案例:将c.txt的内容复制到d.txt。
public static void main(String[] args) throws Exception {
File f1 = new File("D:/aa/bb/cc/c.txt");
File f2 = new File("D:/aa/bb/cc/d.txt");
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] bytes = new byte[10];
int n;
while ((n = in.read(bytes)) != -1) {
out.write(bytes,0,n);
}
}
结果: