输入流和输出流
按照流的流向来分,可以分为输入流和输出流。输入,输出都是从程序运行所在内存的角度来划分的。
输入流:只能从中读取数据,而不能向其写入数据,由InputStream和Reader作为基类。
输出流:只能向其写入数据,而不能从中读取数据。由OutputStream和Writer作为基类。
这是在d盘中创建一个a的文件,然后再a文件中写入。
public static void main(String[] args) throws IOException {
File f1 = new File("d:/a");
f1.createNewFile();
OutputStream out = new FileOutputStream(f1);
// Scanner sc = new Scanner(System.in);
// System.out.println("请输入:");
// String msg = sc.next();
String msg1 ="爱你在每一个你不知道的瞬间";
byte[] bytes = msg1.getBytes();//获取字符串对应解析后的 byte[]数组
out.write(bytes);
}
读取文件中的内容 使用这个代码之前必须先创建在磁盘里创建一个a.txt文件,文件中要写入几个字母
public static void main(String[] args) throws IOException {
/**
* 使用这个代码之前必须先创建在磁盘里创建一个a.txt文件,文件中要写入几个字母
*/
//输出流:内存的内容输出到文件(写操作) 输入流:文件内容输入到内存中(读操作)
File f1=new File("d:/a.txt");
//创建一个输入流,读取f1这个文件
InputStream input = new FileInputStream(f1);
//读取文件的一个字符,然后把字符转换为对应的数字放回。如果读取到文件的末尾,返回的是-1
// int n;
// while ((n=input.read())!=-1){
// System.out.println((char)n);
// }
//int read(byte[] b)使用缓冲区读取: 一次读取数组长度个元素,读取到的字符转换成数字存入数组中
// byte[] b=new byte[10];//定义byte数组,指定长度,作为每次读取的缓冲区
// int n = input.read(b);//按照数组长度读取,读取的内容存在数组中,返回的是实际读取的字节数
// System.out.println("读取的字节数:"+b);
// String s = new String(b,0,n);//对数组 从 0 索引开始 截取实际读取的长度10产生字符串
// System.out.println(s);
//
// byte[] b1=new byte[10];
// int n1 =input.read(b1);//要求读十个,实际只有 5个 b数组中有五个是无效数据
// System.out.println("读取的字节数:"+n1);
// String s1 =new String(b1,0,n1);
// System.out.println(s1);
//
// byte[] b2=new byte[10];
// int n2=input.read(b2);
// System.out.println("读取的字节数:"+n2);
// String s2=new String(b2,0,-1);
// System.out.println(s2);
//因为上面重复的代码过多,所以下面这个直接使用循环判断
byte[] buffer=new byte[10];
while (true) {
int n = input.read(buffer);
if (n!=-1){
String s = new String(buffer,0,n);
System.out.print(s);
}else{
break;
}
}
}
输入流,输出流 综合案例:
public static void main(String[] args) throws IOException {
//1.定义源文件和目的文件的文件对象
File f1= new File("d:/a.txt");
File newFile= new File("d:/a/b.txt");
//2.创建目的文件
newFile.createNewFile();
//3.定义输入流: 使用输入流读取内容 使用输出流写入内容
InputStream in =new FileInputStream(f1);
OutputStream out=new FileOutputStream(newFile);
//4.循环读取文件内容,同时写入指定的文件
// int n;
// while ((n=in.read())!=-1){
// out.write(n);
// }
//实际工作中推荐写法
// byte[] buffer=new byte[10];
// int n=0;
// while ((n=in.read(buffer))!=-1){
// out.write(buffer,0,n);//把buffer数组从0开始,截取读取到有效字节数n 写入到目的文件中
// }
//联系时容易理解的方式
byte[] buffer=new byte[10];
int n=0;
while (true){
n=in.read(buffer);//读取文件,内容放入buffer数组中,返回的是实际读取的字节数
if (n!=-1){
out.write(buffer,0,n);//把buffer数组从0开始,截取读取到有效字节数n 写入到目的文件中
}else{
break;
}
}
}