java的IO系统

来源:互联网 发布:linux通过终端发邮件 编辑:程序博客网 时间:2024/05/24 04:37

是读取还是写入是参照与内存的,数据进入内存即为输入,从内存写入其他设备即为输出。(硬盘到内存是输入流,内存到硬盘是输出流)

所有的文件在计算机里面都是以二进制的形式储存的。
不同的文件在计算上显示的效果不一样,主要以后缀名来区分

字节流:以字节的形式读取数据
InputStream——FileInputStream 字节流,读取数据
OutputStream—–FileOutputStream 字节流,写入数据
字符流:以字符的形式读取数据
Reader———–BufferedReader 字符流,读取数据
Writer———–BufferedWriter 字符流,写入数据

输入流
public static void main(String[] args) {//把文件里面的信息打印出来
File f = new File(“J:\上机作业.txt”);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte b[] = new byte[1024];
int len = fis.read(b);//如果读到文件结尾的话返回-1,没有到文件结尾的话表示读到字节数组中的长度.
/*从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
也就是说每次读取1024个字节,没有读完的话将继续读取直到读完为止。
*/
while(len!=-1){
// String str = new String(b);
String str1 = new String(b, 0, len);
System.out.println(str1);
len = fis.read(b);//改变循环条件
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭流
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

输出流
public static void main(String[] args) {
File f = new File(“E:\第九课\ArrayList\制作文本.txt”);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
System.out.println(“请输入一段信息把它存储到文本当中!”);
Scanner sca = new Scanner(System.in);
String str = sca.next();//接收客服端输入的信息
byte b[] = str.getBytes();//把字符串转换成字节
fos.write(b);//把接收到的信息通过write()方法输入到文本当中
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭流
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

复制(输入流与输出流的结合)
public static void main(String[] args) {
File f1 = new File(“J:\上机作业.txt”);
File f2 = new File(“J:\制作文本.txt”);
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(f1);
fos = new FileOutputStream(f2);
byte b1[] = new byte[1024];//方法1 麻烦一点
int len = fis.read(b1);//如果到文件结尾的话返回-1,没有到文件结尾的话表示读到字节数组中的长度.
while(len!=-1){
String str = new String(b1, 0, len);
byte b2[] = str.getBytes();
fos.write(b2);
System.out.println(str);//显示效果
len = fis.read(b1);//改变循环条件
}
//方法2 简单一点
// int len = fis.read();//如果到文件结尾的话返回-1,没有到文件结尾的话表示读到字节数组中的长度.
// while(len!=-1){
// fos.write(len);
// len = fis.read();//改变循环条件
// }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭流
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

原创粉丝点击