public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
//绝对位置,根目录D:\workspace\w20210322_17\JavaSE_08_IO\src\com\Test_01.java"
//相对位置,当前目录./src/com/Test_01.java
//创建字节流输入对象
//绝对位置加括号双引号
FileInputStream fileInputStream=new FileInputStream(“D:\Xiaoyuandianshang\eclipse\workspace\JavaSE_08_IO\src\IO\_IO_01.java”);
//必须是找到src么
//相对位置
FileInputStream fileInputStream2 =new FileInputStream("./src/IO/_IO_01.java");
//用read读字节
int s1=fileInputStream.read();
int s2=fileInputStream2.read();
System.out.println(s1);
System.out.println(s2);
//循环读
int temp=0;
// read 读取下一个字节,如果到达文件末尾,返回 -1 ,默认光标在顶端,读一下,向下移动一位,并返回下一位的值
while (fileInputStream.read()!=-1) {
temp =fileInputStream .read();
System.out.print((char)temp);
//单个读会出现乱码
}
//利用byte数组实现
byte bytes[]=new byte[100];
int temb=0;
//ready数组返回值是当前读取的个数,最后返回-1
while ((temb=fileInputStream2.read(bytes ))!=-1) {
String string=new String(bytes,0,temp);
System.out.println(string);
//返回的个数,数组是100读150,先读100 再读五十,读五十的时候temp是150?
}
}
public static void main(String[] args) throws IOException {
FileInputStream file = null;
try {
file=new FileInputStream("./src/IO/_IO_01.java");
//循环读取
byte bytes[]=new byte[100];
int temp=0;
while ((temp=file.read(bytes))!=-1) {
String string = new String(bytes,0,temp);
System.out.println(string);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
file.close();
}
/**
-
步骤 : 1 打开流 2 写出(追加写入/覆盖写入) 3 刷缓存 4 关闭
-
构造方法 :
-
FileOutputStream(String) : 只传递需要写出的文件路径,默认覆盖写出
-
FileOutputStream(String,boolean) : 只传递需要写出的文件路径,第二个参数,如果为true 就是追加写出,false是覆盖写出
-
@param args
*/
public static void main(String[] args)throws IOException {
FileOutputStream file=new FileOutputStream(“E:/123.txt”);
//写单个内容
file.write(97);
byte b[]={97,98,99,100};
//写整个字符串内容
file.write(b);
//写一部分
file.write(b, 0, 2);FileInputStream fileStream=new FileInputStream("E:/123.txt"); byte bb[]=new byte[100]; int temp=0; while ((temp=fileStream.read(bb ))!=-1) { String string=new String(bb,0,temp); System.out.println(string); } //刷缓存 一定有吗? file.flush(); //关闭 file.close();
}