Java IO流操作
Java IO流操作
1:字节流是对二进制文件操作的(图片,音乐,影视文件的操作)
InputStream是一个抽象类,一般都使用它的两个实现的子类(FileInputStream 对二进制文件操作)(ObjectInputStream 对对象进行序列化反序列化操作)。如何想看这些类,JavaAPI自己去查看。
1:FileInpuitStream类 (操作文本文件乱码也已解决)
package com.fileinputstream;
import java.io.*;
import java.util.Scanner;
public class Demm {
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
File file=new File("F:/helloworld/jiahang.txt");
System.out.println("请输入要写的内容:");
String str=input.nextLine();
FileOutputStream fos=new FileOutputStream(file);
fos.write(str.getBytes());
System.out.println("写入完毕!");
fos.close();
FileInputStream fis=new FileInputStream(file);
int temp=0;// 解决方案:byte bytes[]=new byte[1024]; 充当缓存区
byte bytes[]=new byte[1024];
/*while((temp=fis.read())!=-1){//一个字节一个字节的读取文件 解决方案:(temp=fis.read(bytes))!=-1
System.out.print((char) temp); //将字节转成char输出 解决方案:new String(bytes,0,temp) 输出结果 从 0-temp
}*/
while((temp=fis.read(bytes))!=-1){
System.out.print(new String(bytes,0,temp) );
}
fis.close();
}
}
2ObjectInputStream(FileInputStream对象),创建ObjectInputStream对象时,造方法中传入一个FileInputStream对象。创建FileInputStream对象时,构造方法传入一个File对象,就是一个文本地址路径。
package test816;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
/**
* 为了方便测试,现将代码都写到一个类中了。以下是需要注意的两点:
* 1、对象中的transient和static类型成员变量不会被读取和写入
* 2、实现Serializable接口
* @author mengfeiyang
*
*/
public class hell {
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "F:/helloworld/d.txt";
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(path));
Person p1 = new Person("张三", 12, true);
Person p2 = new Person("李四", 33, false);
oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(null);
//如果不写入一个null对象 ,则读取的时候会报异常EOFException ,则需要try catch 捕获异常 (已经注释)
oos.flush();
System.out.println("写入完毕");
ois = new ObjectInputStream(new FileInputStream(path));
Object object = ois.readObject();
while( object !=null){
System.out.println(object.toString());
object = ois.readObject();
}
}
// catch(EOFException e){
// System.out.println("end");
// }
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(oos!= null){
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ois!= null){
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class Person implements Serializable{
private String name ;
private int age;
private boolean sex;
private void Perosn() {
// TODO Auto-generated method stub
}
public Person(String name, int age, boolean sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + (sex?"男":"女") + "]";
}
}
2:IO字符流的操作(对文本文件的操作,对字符串进行编码转换,字节流一个一个读取文本文件太慢啦!!!字符流操作出现,拯救一切!!!嘿嘿嘿)
1:InputStreamReader(InputStream is,charset c).创建InputStreamReader对象时,构造方法传入一个字节流对象,还可以进行编码转化。(只是InputStreamReader和B|ufferedInputStreamReader)的读取操作。
package com.reader;
import java.io.*;
/**
* @Title:${贾天一}
* @Description: [娱乐]
*/
//不管多大的文本,都可以读取。本人已经调试过啦!!!
public class demo {
public static void main(String[] args) {
demo a = new demo();
try {
a.transReadNoBuf();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("--------");
try {
a.transReadByBuf();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void transReadNoBuf() throws IOException {
/**
* 没有缓冲区,只能使用read()方法。
*/
//读取字节流
InputStream in = new FileInputStream("F:\\helloworld\\reader.txt");//读取文件的数据。
//将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节.
//charsetname可以改写字符的编码问题
InputStreamReader isr = new InputStreamReader(in,"utf-8" );//读取
// 跟上面创建一样的效果
//InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\demo.txt"),"gbk");
char []cha = new char[1024];
int len = isr.read(cha);
System.out.println(new String(cha,0,len));
isr.close();
}
public static void transReadByBuf() throws IOException {
/**
* 使用缓冲区 可以使用缓冲区对象的 read() 和 readLine()方法。
*/
//读取字节流
InputStream in = new FileInputStream("F:\\helloworld\\reader.txt");//读取文件上的数据。
//将字节流向字符流的转换。
InputStreamReader isr = new InputStreamReader(in,"utf-8");//读取
//创建字符流缓冲区,BufferedReader 自带缓存区域,不用你自己再去定义(一个像上面那种)【1024】的字节数组进行缓存啦!!!
BufferedReader bufr = new BufferedReader(isr);//缓冲
//跟上面一样的创建效果
//BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\demo.txt")));
//带有缓存区域的可以分开读取文本文件,比如下面三行读取文本文件的一个字,再进行按行读取。
int ch =0;
ch = bufr.read();
System.out.println((char)ch);
String line = null;
while((line = bufr.readLine())!=null){
System.out.println(line);
}
isr.close();
}
}
这里是写入操作
package com.reader;
import java.io.*;
/**
* @Title:${贾天一}
* @Description: [娱乐]
*/
public class demo1 {
public static void main(String[] args) {
demo1 a = new demo1();
try {
a.transWriteNoBuf();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("用OnputStreamWriter输入到F:\\helloworld\\reader1.txt成功");
System.out.println("------------");
try {
a.transWriteByBuf();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("用BufferWriter输入到F:\\helloworld\\reader.txt成功");
}
public static void transWriteNoBuf() throws IOException {
//OutputStream out = System.out;//打印到控制台
OutputStream out = new FileOutputStream("F:\\helloworld\\reader1.txt");//打印到文件
OutputStreamWriter osr = new OutputStreamWriter(out);//输出
//OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream("D:\\demo.txt"));//两句可以综合到一句。
// int ch = 97;//a
// int ch = 20320;//你
// osr.write(ch);
String str = "你好吗?";//你好吗?
osr.write(str);
osr.flush();
osr.close();
}
public static void transWriteByBuf() throws IOException {
//OutputStream out = System.out;//打印到控制台。
OutputStream out = new FileOutputStream("F:\\helloworld\\reader.txt");//打印到文件。
OutputStreamWriter osr = new OutputStreamWriter(out);//输出
//OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream("D:\\demo.txt"));//综合到一句。
BufferedWriter bufw = new BufferedWriter(osr);//缓冲
// int ch = 97;//a
// int ch = 20320;//你
// osr.write(ch);
String str = "你好吗?\r\n我很好!";//你好吗?
bufw.write(str);
bufw.flush();
bufw.close();
}
}
3:FileReader是InputStreamReader的子类,简化InputStreamReader类的复杂操作。创建InputStreamReader对象时需要传入一个InputStream对象。FileReader不用,直接传入一个文本地址路径就可以啦!,但是FileReade类没有编码转化操作。
package com.filereader;
/*
* 文件读取的这种方式:通过字符数组进行读取。比一个一个字符读取快,但是也可以一个一个字符的读取。
* 步骤和一个字符一个字符读取的基本相似,但其中就是多创建一个字符数组
* 犹如不能进行编码转化,中文会出现乱码行为。
*/
import java.io.*;
public class demo1 {
public static void main(String[] args)
{
FileReader fr=null;
try
{
fr=new FileReader("F:\\helloworld\\filereader.txt");
char[] buf=new char[1024];
//read(char [])返回读到的字符个数
int num=0;
while((num=fr.read(buf))!=-1) //读取文件并把它存入buf中,用num返回读到字符的个数,一直读到结尾
{
System.out.print((new String(buf,0,num)));//字符数组里仍有空白没有读入的位置,所以不要了
//new String(字符串,开始位置,结尾位置)
}
}
catch(IOException e)
{
System.out.println(e.toString());
}
finally
{
try
{
if(fr!=null)
{
fr.close();
}
}
catch(IOException e)
{
System.out.println(e.toString());
}
}
}
}
FileWriter输入操作
package com.filereader;
import java.io.*;
public class hell {
public static void main(String[] args) throws IOException {
File file = new File("F:\\helloworld\\test.txt");
FileWriter fw = new FileWriter(file);
fw.write(97); //会转化为字符,97是ASCALL值,输入小写字符a
fw.write("this is 我们"); //把字符串输入指定文本中
fw.close();
System.out.println("字符串输入到F:\\helloworld\\test.txt成功!!!");
}
}