IO流
* 流的本质就是数据传输
*
*
* 流是一组有顺序的,有起点有终点的字节集合,是对数据传输的总称或抽象
*
* 简单来说,就是设备之间数据传递称为流
*
* 流的本质, 就是数据的传输,根据不同的数据传输特性,抽象出各种类,方便我们直接操作数据‘
*
*
* 流中的操作对象是指内存中,当前操作的程序而言
*
* 输入:往内存中导入数据
*
* 输出:指从内存中写出数据
*
* I: input 数据
* O: output 写出
*
* 四大抽象类
*
*
* InputStream 字节输入
*
* OutputStream 字节输出
*
* Writer 字符输出
*
* Reader 字符输入
*
*
* 原始文件流:用于打开链接,操作数据
*
* 文件流
*
* FileInputStream 字节输入
*
* FileOutputStream 字节输出
*
* FileReader 字符输入
*
* FileWriter 字符输出
* 一切皆文件
*
* java.io.InputStream
*
*
* java.io.FileInputStream 按照字节的方法读取数据,在原始文件
*
*
* 想要读取一个文件,必要找到他
*
* 定位到某个文件有两种方式 1 绝对路径 2 相对路径
*
*
* 相对当前文件 如何找到 相对路径 ./当前目录 ../下级
*
* 以系统根目录为准 ,如何找到这个文件 绝对路径
public static void main(String[] args) {
//在Eclipse 相对
FileInputStream fis = null;
try {
//创建对象 使用相对路径找这个文件
fis = new FileInputStream("./src/_01_IO/IO_01.java");
// FileInputStream fis = new FileInputStream("./src/_01_IO/IO_02FileIntputStream");
//读取数据
//读取一个字节,返回下一个字节的值,因为喀什光标在顶端,如果达到文件末尾就返回-1
int i1 =fis.read();
System.out.println((char)i1);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if (fis !=null) {
fis.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
常用方法
public class IO_06_FileInputStream {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("./src/_01_IO/IO_01.java");
//可获得字节数
System.out.println(fis.available());
// 3 读取字节数组
byte [] bytes = new byte[5];
fis.read(bytes);
System.out.println(new String(bytes));
System.out.println(fis.available());
//4跳过不读
fis.skip(30);
System.out.println(fis.available());
//5读取一个
System.out.println(fis.read());
//6关闭资源
fis.close();
}
打印流
public static void main(String[] args) {
//复制就是输入和输出
//先获取数据
//在输出数据
try(
FileInputStream fis = new FileInputStream("D:/123.txt");
FileOutputStream fos = new FileOutputStream("E:/123.txt");
PrintStream ps = new PrintStream(fos);
) {
byte [] bytes = new byte[1024];
int tmp =0;
while ((tmp = fis.read(bytes)) != -1) {
ps.print(new String(bytes,0,tmp));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}