二进制文件 : 声音,视频,图片
输入流: 将硬盘的文件读入java 的内存中
输出流: 将Java中的文件输出到硬盘中
1 首先创建文件 字节输入流
//创建file对象
File file = new File("D:\test.txt")
//创建text.txt 文件
file.createNewFile();
2 获取文件信息
File file= new File(); file.CreateNewFile(); file.isDirectory() //得出文件内容的字节长度(数字和字母为1个字节,汉字是3个字节) file.length(); file.exists(); file.getName(); file.isFile();
3
1 inputStream 是由抽象类修饰的不能直接创建
2Reader
3他们的继承关系
4 读取D盘下的文件:
public class StreamInput {
public static void main(String[] args) {
String filePath="D:\test1.txt";
int readData=0;
FileInputStream fileInputStream =null;
try {
fileInputStream=new FileInputStream(filePath);
while((readData=fileInputStream.read())!=-1){
char readData1 = (char) readData;
System.out.print(readData1);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
汉字用char 类型的话会出现乱码,所以汉字多用字符流
4 FileInputStream and FileOutputStream
public class IOoutputStream {
public static void main(String[] args) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("D:\tt11.txt");
String str = "hello,world";
// 将字符串转成一个字符数组 fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8))
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1 就是文件输入流会覆盖原来的文件里的内容,
FileOutputStream(“D:tt11.txt”,true);k可以防止文件里的内容覆盖
2 将字符串转成字符串
String str =""
str.getBytes();
5 字符输入流 fileReader fileweiter`
public class CharStreamOr {
// 字符输入流
public static void main(String[] args) {
FileReader fileReader = null;
int readLen = 0;
char[] chars = new char[8];
try {
fileReader = new FileReader("D:\test1.txt");
while ((readLen =fileReader.read(chars))!=-1){
//定义了字符长度
System.out.println(new String(chars, 0, readLen));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
6字符输出流
public class CharWriterOr {
public static void main(String[] args) {
FileWriter fileWriter = null;
char[] chars={'x','c','v'};
try {
fileWriter = new FileWriter("D:\tt.txt",true);
fileWriter.write("qwer");
fileWriter.write(chars);
//获取索引为0 到3 的数据
fileWriter.write("猪猪侠童话里做英雄!".toCharArray(),0,3);
fileWriter.write("猪猪");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
7 buffer 读入读出
public static void main(String[] args) {
String line ;
BufferedReader bufferedReader =null;
try {
bufferedReader = new BufferedReader(new FileReader("D:\tt.txt"));
while ((line = bufferedReader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}



