Java基础--IO


1.IO流

Java操作数据时通过流的方式。

IO流用来处理设备之间的数据传输

Java用于操作流的对象都在IO包中

  • 按照流向分为输入流和输出流。
  • 按照数据类型分为字符流和字节流。

2.IO流常用基类
2.1字节流的抽象基类:

InputStream ,OutputStream。

2.2字符流的抽象基类:

Reader ,Writer。

注:由这四个类派生出来的子类名称都是 以其父类名作为子类名的后缀。

如:InputStream的子类FileInputStream。

如:Reader的子类FileReader。

3.IO程序的书写
    1. 导入IO包中的类
    2. 进行IO异常处理
    3. 对流进行关闭

4.字符流——创建文件

4.1字符流的由来:

其实就是:字节流读取文字字节数据后,不直接操作而是先查指定的编码表。获取对应的文字。

在对这个文字进行操作。简单说:字节流+编码表 

1.创建流对象,建立数据存放文件
FileWriter fw = new FileWriter(“Test.txt”);
2.调用流对象的写入方法,将数据写入流
fw.write(“text”);
3.关闭流资源,并将流中的数据清空到文件中。

fw.close();

注意:
1.定义文件路径时,可以用“/”或者“\\”。
2.在创建一个文件时,如果目录下有同名文 件将被覆盖。
3.在读取文件时,必须保证该文件已存在,否则出异常。
public class FlieWriterDemo {
	// 创建可以往文件中写入字符数据的字符输出流对象
	// 既然是往文件中写入文字数字,那么在创建对象时,就必须明确该文件用于存储数据的目的地

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		FileWriter fw = new FileWriter("Demo.txt", true);// 没true就会发生覆盖
		fw.write("hello" + System.getProperty("line_separator"));// 换行
		fw.flush();
		fw.write("大家好");
		fw.write("\r\n哈哈");// 换行
		fw.write("good bye");
		fw.close();//关流

	}

}


4.2 IO 异常处理

public class FlieWriteIOException {

	public static void main(String[] args) {
		
		FileWriter fw=null;
		try {
			fw=new FileWriter("Demo2.txt");
			fw.write("FileWriter");
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		finally{
			if (fw!=null)
			try {
				fw.close();
			} catch (Exception e2) {
				throw new RuntimeException("无法关闭");
			}
		}
	}

public class ReaderWriter {
//	将C盘的一个文本文件复制到d盘
//	复制其实就是连读带写

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		FileReader fr=new FileReader("c:\\file.txt");//关联文件,抛异常
		FileWriter fw=new FileWriter("d:\\file.txt");//创建文件,抛异常
		char[] buf=new char[1024];
		int len=0;
		while((len=fr.read(buf))!=-1){
			System.out.println(buf);
			fw.write(new String(buf,0,len));
		}
		fr.close();//关闭资源
		fw.close();

	}

}


public class ReaderWriterTest {

	public static void main(String[] args) {
	
	FileReader fr=null;//外面声明
	FileWriter fw=null;//
	try {
		fr=new FileReader("Demo.txt");//里面引用
		fw=new FileWriter("copyDemo.txt");
		char[] buf=new char[1024];//创建一个字符数组,相对于缓冲区
		int len=0;
		while((len=fr.read(buf))!=-1){
			fw.write(buf, 0, len);
		}
	} catch (Exception e) {
		// TODO: handle exception
		throw new RuntimeException("读写失败");
		
	}
	finally{
		if(fw!=null)
			try {
				fw.close();
			} catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace();
				
			}
		if(fw!=null)
			try {
				fw.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
	}

}

public class FileReaderDemo{
	//读取一个文本文件,将读取到的文字打印到控制台
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		//创建一个能读取数据的流对象。
		//在创建读取对像时,必须要明确读取的文件一定要确定该文件时存在的
		FileReader fr=new FileReader("Demo.txt");//关联文件
	
		char[] buf=new char[1024];//创建一个字符数组容器1024比较好
		int len=0;
		while((len=fr.read(buf))!=-1){
			System.out.println(new String(buf,0,len));//分配一个新的 String
		}
		fr.close();
	}

}


5.字符流缓冲区

5.1字符流的缓冲区

缓冲区的出现提高了对数据的读写效率。

5.2对应类

BufferedWriter

BufferedReader

5.3缓冲区要结合流才可以使用,在流的基础上对流的功能进行了增强。


public class ReadLineDemo {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bufr = new BufferedReader(new FileReader("Demo1.txt"));// 读取缓冲区
		BufferedWriter bufw = new BufferedWriter(
				new FileWriter("CopyDemo1.txt"));// 写入缓冲区
		String line=null;
		
		while((line=bufr.readLine())!=null){//按行读取
			bufw.write(line);
			bufw.newLine();//换行
			bufw.flush();
		}	

		bufr.close();
		bufw.close();
	}

}


6.装饰设计模式

6.1对一组对象进行功能的增强时,就可以使用该模式进行问题的解决。

6.2装饰和继承都能实现一样的特征:进行功能的增强。

区别:装饰比继承灵活,避免继承的臃肿

特点:装饰和别装饰类必须所属同一个接口或父类。

public class WrapperDemo {

	public static void main(String[] args) {

		PersonE p = new PersonE();

		NPerson p1 = new NPerson(p);
		p1.eat();

		NewPerson2 p2 = new NewPerson2();
		p2.eat();
	}

}

class PersonE {
	void eat() {
		System.out.println("吃饭");
	}
}

// 这个类的出现是为了增强Person而出现的。这是装饰
class NPerson {
	private PersonE p;

	NPerson(PersonE p) {
		this.p = p;
	}

	public void eat() {
		System.out.println("开胃酒");
		p.eat();
		System.out.println("甜点");

	}

}
//这是继承
class NewPerson2 extends PersonE {
	public void eat() {
		System.out.println("开胃酒");
		super.eat();
		System.out.println("甜点");

	}
}


7.字节流

基本操作与字符流类相同

但它不仅可以操作字符,还可以操作其他 媒体文件。

public class CopyMp3 {
	//复制一个mp3

	public static void main(String[] args) throws IOException {

			FileInputStream fis = new FileInputStream("E:\\MP3爱情转移.mp3");
			FileOutputStream fos = new FileOutputStream("D:\\爱情转移3.mp3");
			
			int len = 0;
			while ((len = fis.read()) != -1) {
				fos.write(len);
			}
			fis.close();//关流
			fos.close();
		
		
	}
}

8.字节流的缓冲区

字节流的缓冲区同样是提高了字节流的读写效率。

public class CopyMp3 {
	// 几种复制一个mp3的方法

	public static void main(String[] args) throws IOException {
		copyMp3_1();
		copyMp3_2();
		copyMp3_3();
		copyMp3_4();

	}

	// 效率太慢,不建议使用
	public static void copyMp3_4() throws IOException {
		// TODO Auto-generated method stub
		FileInputStream fis = new FileInputStream("E:\\MP3爱情转移.mp3");
		FileOutputStream fos = new FileOutputStream(":\\爱情转移3.mp3");

		int len = 0;
		while ((len = fis.read()) != -1) {
			fos.write(len);
		}
		fis.close();// 关流
		fos.close();

	}

	public static void copyMp3_3() throws IOException {
		// TODO Auto-generated method stub
		FileInputStream fis = new FileInputStream("E:\\MP3\\Songs\\爱情转移.mp3");
		FileOutputStream fos = new FileOutputStream("E:\\爱情转移2.mp3");
		byte[] buf = new byte[fis.available()];// 创建一个与文件大小一致的数组,不建议使用
		fis.read(buf);
		fos.write(buf);
		fis.close();
		fos.close();

	}

	// 建议使用
	public static void copyMp3_2() throws IOException {
		// TODO Auto-generated method stub
		FileInputStream fis = new FileInputStream("E:\\360图\\1.jpg");
		BufferedInputStream bufis = new BufferedInputStream(fis);// 添加读缓冲区
		FileOutputStream fos = new FileOutputStream("E:\\1.jpg");
		BufferedOutputStream bufos = new BufferedOutputStream(fos);// 添加写缓冲区

		int len = 0;
		while ((len = bufis.read()) != -1) {
			bufos.write(len);

		}

		bufis.close();
		bufos.close();
	}

	// 建议使用
	public static void copyMp3_1() throws FileNotFoundException, IOException {
		FileInputStream fis = new FileInputStream("E:\\MP3\\Songs\\爱情转移.mp3");
		FileOutputStream fos = new FileOutputStream("E:\\爱情转移.mp3");
		byte[] buf = new byte[1024];// 创建一个1024的数组
		int len = 0;
		while ((len = fis.read(buf)) != -1) {
			fos.write(buf, 0, len);
			fos.flush();// 刷新
		}
		fis.close();// 关流
		fos.close();
	}

}


9.键盘录入

public class ReadKeyDemo {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		readKey1();
	}
/*
 * 获取用户键盘录入的数字
 * 并将数据大写显示在控制台上
 * 如果输入的是over则结束
 * 
 * 注意:键盘录入只读取一个字节
 */
	public static void readKey1() throws IOException {
		// TODO Auto-generated method stub
		InputStream in=System.in;
		StringBuilder sb=new StringBuilder();//创建一个容器
		
		int ch=0;
		while((ch=in.read())!=-1){//循环读取,可无法停止除了按按钮,read()阻塞式方法,一次只能读一个字节
			if(ch=='\r')
			continue;
			if(ch=='\n'){//判断是否是回车
				String temp=sb.toString();
				if("over".equals(temp))//判断是否是over
					break;
				System.out.println(temp.toUpperCase());//转换成大写
				sb.delete(0, sb.length());//回车后每次清零
			}
			else
			sb.append((char)ch);//添加
			
		}
				
	}


}

10.转换流

10.1 InputStreamReader,OutputStreamWriter

InputStreamReader :字节到字符的桥梁。解码。

OutputStreamWriter:字符到字节的桥梁。编码。

10.2转换流的由来

字符流与字节流之间的桥梁

方便了字符流与字节流之间的操作

10.3转换流的应用

字节流中的数据都是字符时,转成字符流操作更高效。

10.4什么时候使用转换流呢?
1.源或者目的对应的设备是字节流,但是操作的却是文本数据,可以使用转换作为桥梁。
提高对文本操作的便捷。
2.一旦操作文本涉及到具体的指定编码表时,必须使用转换流 。

public class TransStream {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		transDemo();
		transDemo2();
		transDemo3();
		transDemo4();
		transDemo5();
		transDemo6();
		transDemo7();

	}
	//1.将录入数据写入一个文本文件中2
	public static void transDemo7() throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bufw=new BufferedWriter(new FileWriter("你好.txt"));
		String line=null;
		while((line=bufr.readLine())!=null){
			if("over".equals(line))
				break;
			bufw.write(line);
			bufw.newLine();
			bufw.flush();
			
			
		}
		bufw.close();
		
	}
	
	//1.将录入数据写入一个文本文件中
	public static void transDemo6() throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("TreansDemo.txt")));
		String line=null;
		while((line=bufr.readLine())!=null){
			if("over".equals(line))
				break;
			bufw.write(line);
			bufw.newLine();
			bufw.flush();
			
			
		}
		bufr.close();
		bufw.close();
		
	}
	//将读取的文本文件显示在控制台上 
	public static void transDemo2() throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bufr=new BufferedReader(new InputStreamReader(new FileInputStream("Demo.txt")));
		BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out));
		String line=null;
		while((line=bufr.readLine())!=null){
			if("over".equals(line))
				break;
			bufw.write(line);
			bufw.newLine();
			bufw.flush();
		}
		bufr.close();
		bufw.close();
		
	}
	
	//将读取的文本文件显示在控制台上 2
			public static void transDemo5() throws IOException {
				// TODO Auto-generated method stub
				BufferedReader bufr=new BufferedReader(new InputStreamReader(new FileInputStream("Demo.txt")));
				String line=null;
				while((line=bufr.readLine())!=null){
					if("over".equals(line))
						break;
					System.out.println(line);
					
				}
				bufr.close();
			}
	//将读取的文本文件复制到另一个文本中1
	public static void transDemo3() throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bufr=new BufferedReader(new InputStreamReader(new FileInputStream("Demo.txt")));
		BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Demo2.txt")));
		String line=null;
		while((line=bufr.readLine())!=null){
			if("over".equals(line))
				break;
			bufw.write(line);
			bufw.newLine();
			bufw.flush();
		}
		bufr.close();
		bufw.close();
	}
	
	//将读取的文本文件复制到另一个文本中2
	public static void transDemo4() throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bufr=new BufferedReader(new FileReader("Demo.txt"));
		BufferedWriter bufw=new BufferedWriter(new FileWriter("Demo3.txt"));
		String line=null;
		while((line=bufr.readLine())!=null){
			if("over".equals(line))
				break;
			bufw.write(line);
			bufw.newLine();
			bufw.flush();
		}
		bufr.close();
		bufw.close();
		
	}
	
	//将读取的文本文件显示在控制台上 
	public static void transDemo() throws IOException {
		// TODO Auto-generated method stub
		
		//键盘录入
		BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));//读取的源地址
		
		//输出
		BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out));//输出的目的地
		String line=null;
		while((line=bufr.readLine())!=null){
			if("over".equals(line))
				break;
			bufw.write(line);
			bufw.newLine();
			bufw.flush();
			
		}
		
		
	}
}


11.流的操作规律

1.明确源和目的

源:

InputStream 

Reader

目的:

OutputStream

Writer

2.明确数据是否是纯文本

源:

不是:InputStream 

是:Reader

目的:

不是:OutputStream

是:Writer


3.明确具体的设备


源设备:
硬盘:file
键盘:System.in
内存:数组
网络:socket
目的:

硬盘:file

键盘:System.out

内存:数组
网络:socket

4.是否需要额外能

1.是否需要高效

是:加上Buffere

2.是否需要转换

是:将字节流转成字符流:InputStreamReader

12.File类

  1. 用来将文件或者文件夹封装成对象
  2. 方便对文件与文件夹的属性信息进行操作 。
  3. File对象可以作为参数传递给流的构造函数。
File对象常见的方法:

1.获取:

getName():获取文件名

getAbsolutePath():获取文件绝对路径

getLength():获取文件大小

lastModified():获取文件最后修改时间

2.创建、删除

creatNewFile():如果文件不存在则创建,如果存在则不创建

deleteFile():删除文件

deleteOnExit():退出时删除文件

mkdir():创建目录

mkdirs():创建多级目录

3.判断

exists():判断文件是否存在

isFile():判断是否文件

isDiretory():判断是否是目录

4.重命名

renameTo():重命名

5.其他

listRoot():系统根目录

getFreeSpace():剩余空间

getTotalSpace():总空间

getUsableSpace():JVM 可用空间

注:调用List方法,file对象中封装的必须是目录,否则会发生空指针异常,如果访问系统目录也会发生空指针异常,如果目录存在但是没有内容,会返回一个数组,但是长度为0。


public class FileDemo {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		constructorDemo();
		getName();
		createAnDeleteDemo();
	}

	public static void createAnDeleteDemo() throws IOException {
		// TODO Auto-generated method stub
		File file=new File("file.txt");
		boolean b=file.createNewFile();
		System.out.println(b);
	}

	public static void constructorDemo() {
		// TODO Auto-generated method stub
		File f=new File("D:\\Users\\Dacky\\workspace\\JavaExc\\bin\\Array2Demo.class");
		File file1=new File("c:\\","nihao");
		File file2=new File("c:\\");
		File fiel3=new File(file2,"nihao");
		File file4=new File("C:"+System.getProperty("file.separator")+"nihao");//文件分隔符
		File file5=new File("c:"+File.separator+"nihao");
		System.out.println(file4);
		System.out.println(file5);
		
	}
	public static void getName(){
	File file=new File("D:\\Users\\Array2Demo.class");
	File[] files=file.listFiles();
	String name=file.getName();
	String abspath=file.getAbsolutePath();//决对路径
	String path=file.getPath();//相对路劲
	long len1=file.length();//文件大小
	long time=file.lastModified();//最后的修改时间
	long len=file.getFreeSpace();//剩余空闲空间
	System.out.println("name"+name);
	System.out.println("abspath"+abspath);
	System.out.println("path"+path);
	System.out.println("len1"+len1);
	System.out.println("time"+time);
	System.out.println("len"+len);
	Date date=new Date(time);
	DateFormat dateFormat=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
	String str=dateFormat.format(date) ;
	System.out.println("time"+str);
	
	}
}


12.1 过滤器(Filter)

public class FileDemo1 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub

		reName();
		listRootDemo();
		listDemo();
		FilterDemo();
		FilterDemo_2();

	}

	public static void FilterDemo_2() {
		// TODO Auto-generated method stub
		File f = new File("D:\\Users\\Dacky\\workspace\\JavaExc");
		File[] names = f.listFiles(new FilterByHidden());// 加入过滤器
		for (File name : names) {
			System.out.println(name);
		}

	}

	public static void FilterDemo() {
		// TODO Auto-generated method stub
		File f = new File("D:\\Users\\Dacky\\workspace\\JavaExc");

		String[] names = f.list(new SuffixFilter(".txt"));// 加入过滤器
		for (String name : names) {
			System.out.println(name);
		}

	}

	public static void listDemo() {
		// TODO Auto-generated method stub
		File f = new File("f:\\ ");
		// 调用list的方法file对象中封装必须是目录,否则会发生NullPointerException;
		// 如果访问的是系统级目录也会发生空指针异常
		String[] names = f.list();// 文件目录
		// 遍历文件,包含隐藏文件
		for (String name : names) {
			System.out.println(name);
		}

	}

	public static void listRootDemo() {
		// TODO Auto-generated method stub
		File file = new File("d:\\");
		System.out.println("getFreeSpace:" + file.getFreeSpace());// 空闲空间
		System.out.println("getTotalSpace:" + file.getTotalSpace());// 总空间
		System.out.println("getUsableSpace:" + file.getUsableSpace());// JVM可用空间

	}

	public static void reName() {
		// TODO Auto-generated method stub
		File f = new File("renameDemo.txt");
		// 位置不同的重命名会把源文件剪切掉
		File f2 = new File("D:\\Users\\Dacky\\workspace\\renameDemo.txt");

		f2.renameTo(f);

	}

}

// 过滤器
class FilterByHidden implements FileFilter {

	@Override
	public boolean accept(File pathname) {
		// TODO Auto-generated method stub
		return !pathname.isHidden();
	}

}

// 过滤器
class SuffixFilter implements FilenameFilter {

	private String suffix;

	public SuffixFilter(String suffix) {
		super();
		this.suffix = suffix;
	}

	@Override
	public boolean accept(File dir, String name) {
		// TODO Auto-generated method stub
		return name.endsWith(suffix);
	}

}


13.递归

递归:函数自身直接或间接调用到自身

注意:1.递归一定要明确条件,否则容易栈溢出。

   2.注意递归的次数。


递归的使用:

一个功能在被重复使用,并且每次使用时,参与运算的结果与上一次调用有关,这时就可以使用递归来解决问题。


//删除一个带内容的目录
public class DeleteDirDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File dir=new File("D:\\Users\\Dacky\\workspace\\JavaExc\\bin\\1");
		deleteDirDemo(dir);

	}

	public static void deleteDirDemo(File dir) {
		// TODO Auto-generated method stub
		//遍历文件目录
		File[] files=dir.listFiles();
		for(File file:files){
			if(file.isDirectory())
				deleteDirDemo(file);//递归
			else{
				//删除文件
			System.out.println(file+":"+file.delete());
			}
				
		}
		//删除目录
		System.out.println(dir+":"+dir.delete());
		
	}

}


14.Properties集合

Map--->HashTable--->Properties

特点:

1.该集合的键和值都是字符串类型。

2.集合中的数据可以保存到流中,或者从流中获取。

3.通常用来操作以键值对形式存在的配置文件。

public class PropertiesDemo1 {
	/*
	 * 读取一个配置文件
	 * 修改内容
	 * 存储文件
	 * 
	 */

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		//创建文件对象,确保文件存在
		File file=new File("D:\\inf.txt");
		if(!file.exists())
			file.createNewFile();
		
		BufferedReader bufr=new BufferedReader(new FileReader(file));//关联文件
		
		Properties prop=new Properties();//创建properties对象
		
		prop.load(bufr);//加载文件
		
		 prop.setProperty("wangwu", "18");//修改文件
		
		 BufferedWriter bufw=new BufferedWriter(new FileWriter(file)); //创建写入流
		 
		 prop.store(bufw, "");//保存文件
		
		prop.list(System.out);//输出内容
		bufr.close();
		bufw.close();

	}

}


14.IO包中的其他类

14.1打印流

PrintWriter与PrintStream

可以直接操作输入流和文件。

1.提供了打印方法可以对多种数据类型值进行打印。并保持数据的表示形式。

2 .不抛IOException.

14.1.1PrintStream构造函数,接收三种类型的值:

1.字符串路径

2.File对象

3.字节输出流

14.1.2 printerWriterPrintStream构造函数,多接收一种类型的值:字符输出流。

public class PrintStreamDemo {

	public static void main(String[] args) throws IOException {


		PrintStream out = new PrintStream("print.txt");
		

		out.write(610);//只写最低8位,
		
		out.print(97);//将97先变成字符保持原样将数据打印到目的地。 
		
		out.close();	
		
	}

}

14.2序列流

SequenceInputStream

对多个流进行合并。

//读取3个文本文件将其放入一个文件中
public class SequenceStreamDemo {

	public static <E> void main(String[] args) throws IOException {
		ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();
		for(int x=1;x<=3;x++){
			
			al.add(new FileInputStream(x+".txt"));
		}
		Iterator<FileInputStream> it=al.iterator();
		Enumeration<FileInputStream> en=new Enumeration<FileInputStream>() {

			@Override
			public boolean hasMoreElements() {
				// TODO Auto-generated method stub
				return it.hasNext();
			}

			@Override
			public FileInputStream nextElement() {
				// TODO Auto-generated method stub
				return it.next();
			}
			
		};
		SequenceInputStream  sis=new SequenceInputStream(en);
		FileOutputStream fos=new FileOutputStream("42.txt");
		byte[] buf=new byte[1024];
		int len=0;
		while((len=sis.read(buf))!=-1){
			fos.write(buf, 0, len);;
		}
		
		fos.close();
		sis.close();
		
	}

}

14.3操作对象

ObjectInputStream与ObjectOutputStream

被操作的对象需要实现Serializable (标记接口);

注:非静态非瞬态的成员才可以被读取。

若非静态数据不想被序列化可以使用transient这个关键字修饰。 

public class ObjectInputOutpStreamDemo {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		// TODO Auto-generated method stub
		objectRead();
		objectWrite();

	}

	private static void objectWrite() throws IOException, IOException {
		// TODO Auto-generated method stub
		ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("obj.object"));
		//写文件
		oos.writeObject(new Person("wangqiang",30));
		oos.close();
		
	}

	private static void objectRead() throws IOException, IOException, ClassNotFoundException {
		// TODO Auto-generated method stub
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.object"));//关联文件
		Person p=(Person)ois.readObject();//强转和读文件, 被操作的对象需要实现Serializable 
		System.out.println(p.getName()+":"+p.getAge());
		ois.close();
		
	}

}
/*
 * Serializable:用于给被序列化的类加入ID号。
 * 用于判断类和对象是否是同一个版本。 
 * transient:非静态数据不想被序列化可以使用这个关键字修饰。 
 */
class Person implements Serializable/*标记接口*/ {

	private static final long serialVersionUID = 1789757;
	private transient String name;
	private static int age;
	
	
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	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;
	}
	
}

14.4管道流PipedStream 

多线程

public class PipedStream {

	public static void main(String[] args) throws IOException {

		PipedInputStream input = new PipedInputStream();
		PipedOutputStream output = new PipedOutputStream();
		
		input.connect(output);//关联
		
		new Thread(new Input(input)).start();
		new Thread(new Output(output)).start();
		
	}

}


class Input implements Runnable{
	
	private PipedInputStream in;
	Input(PipedInputStream in){
		this.in = in;
	}
	public void run(){
		
		try {
			byte[] buf = new byte[1024];
			int len = in.read(buf);
			
			String s = new String(buf,0,len);
			
			System.out.println("s="+s);
			in.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}

class Output implements Runnable{
	private PipedOutputStream out;
	Output(PipedOutputStream out){
		this.out = out;
	}
	public void run(){
		
		try {
			Thread.sleep(5000);
			out.write("hi!Iam coming".getBytes());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

14.5操作基本数据类型

DataInputStream与DataOutputStream

public class DataSteamDemo {

	public static void main(String[] args) throws IOException {
		
		writeData();
		readData();
		
	}

	public static void readData() throws IOException {
		
		DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
		
		String str = dis.readUTF();
		
		System.out.println(str);
	}

	public static void writeData() throws IOException {
		
		DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
		
		dos.writeUTF("你好");
		
		dos.close();
		
		
	}

}

14.6操作字节数组

ByteArrayInputStream与ByteArrayOutputStream

public class ByteArrayStreamDemo {

	public static void main(String[] args) {

		ByteArrayInputStream bis = new ByteArrayInputStream("abcedf".getBytes());
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		
		int ch = 0;
		
		while((ch=bis.read())!=-1){
			bos.write(ch);
		}
		
		System.out.println(bos.toString());
	}

}

14.7操作字符数组

CharArrayReader与CharArrayWrite


14.8操作字符串

StringReader 与StringWriter

15.RandomAccessFile

不是io体系中的子类。

1.该对象即能读,又能写。

2.该对象内部维护了一个byte数组,并通过指针可以操作数组中的元素,

3.可以通过getFilePointer方法获取指针的位置,和通过seek方法设置指针的位置。

4.其实该对象就是将字节输入流和输出流进行了封装。 

5.该对象的源或者目的只能是文件。通过构造函数就可以看出。 

public class RandomAccessFileDemo {

	public static void main(String[] args) throws IOException {

			randomWrite();
			readFile();
			writeFile();
		}

	public static void randomWrite() throws IOException {
		RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");

		// 往指定位置写入数据。
		raf.seek(3 * 8);

		raf.write("haha".getBytes());
		raf.writeInt(108);

		raf.close();
	}

	public static void readFile() throws IOException {

		RandomAccessFile raf = new RandomAccessFile("random.txt", "r");

		// 通过seek设置指针的位置。
		raf.seek(1 * 8);// 随机的读取。只要指定指针的位置即可。

		byte[] buf = new byte[4];
		raf.read(buf);

		String name = new String(buf);

		int age = raf.readInt();

		System.out.println("name=" + name);
		System.out.println("age=" + age);

		System.out.println("pos:" + raf.getFilePointer());

		raf.close();

	}

	// 使用RandomAccessFile对象写入一些人员信息,比如姓名和年龄。
	public static void writeFile() throws IOException {
		/*
		 * 如果文件不存在,则创建,如果文件存在,不创建
		 */
		RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");

		raf.write("name".getBytes());
		raf.writeInt(97);
		raf.write("age".getBytes());
		raf.writeInt(99);
		//
		raf.close();
	}

}

16.编码解码

Unicode:国际标准码,融合了多种文字。

 中文编码表:GBK、UTK-8

字符串 --> 字节数组:编码。

字节数组 --> 字符串:解码。

public class JieMaBianMa {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stubni
		
		String st="你好";
		byte[] by=st.getBytes("gbk");//编码的过程-60-29-70-61
		
		for(byte b:by){
			System.out.println(b);
		}
		String s=new String(by,"gbk");//解码的过程
		System.out.println(s);
		
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值