IO流总结
来源:互联网 发布:小泉今日子 知乎 编辑:程序博客网 时间:2024/05/22 00:26
1.分布式的编程: 就是序列化这个对象之后,就可以保存这个对象。
2.File对象操作文件和目录的相关方法和文件过滤器的使用(实现这个FilenameFilter接口):
package com.huxin.io.test;import java.io.*;public class FileTest {public static void main(String[] args){ //创建一个file的对象 File file = new File("."); //默认为当前路径,就算没有此目录,它还是不会抛异常 //获取文件名 System.out.println(file.getName()); //获取上一级的路径 System.out.println(file.getParent()); //获取绝对路径 System.out.println(file.getAbsoluteFile()); //获取绝对路径 System.out.println(file.getAbsoluteFile().getParent()); /* * ignullE:\project\my_io\io\ig */// try {//File tempfile = File.createTempFile("aaa", ".txt", file);//tempfile.deleteOnExit(); //jvm在退出的时候,就删除它了// } catch (IOException e) {//e.printStackTrace();// } //创建一个文件的对象 File newFile = new File("ha"); //file的参数应该为当前路径// System.out.println(newFile.exists());// try {////这个方法很有意思,当这个文件的对象不存在的时候,// //他就能创建一个对应的这样的文件。//boolean flag = newFile.createNewFile(); //System.out.println(flag);// } catch (IOException e) {//e.printStackTrace();// } boolean f = newFile.mkdir(); //这个是创建一个目录 System.out.println(f); String[] file3 = file.list(); //打印出当前目录的所有的名字 for(String str:file3){ System.out.println(str); } File[] file4 = File.listRoots(); //打印出根目录 for(File root:file4){ System.out.println(root); }}}package com.huxin.io.test;import java.io.File;import java.io.FilenameFilter;/* * 实现一个FilenameFilter,从而得到一个监听器。 */public class FileNameFilterTest {public static void main(String[] args) { File file = new File("."); //从当前的路径创建一个文件 String[] nameList = file.list(new MyFileNameFilter()); //为了获得当前路径所有的文件名 for(String name :nameList){ System.out.println(name); }}}class MyFileNameFilter implements FilenameFilter{public boolean accept(File dir, String name) { //isDirectory方法表示当前路径表示的文件是否是一个目录return name.endsWith("txt")||new File(name).isDirectory();}}/* * bin ha hello src world.txt */
3. 流这一章: 说白了 就是内存和节点流之间数据的交换。
4. PushbackReader的处理流: 主要是unread的方法
package com.huxin.io.test;/* * 本程序是为了读取冒一个文件的new PushbackReader这个字符串前面的一点内容 */import java.io.*;//注意:读取的时候,空格是代表一个字符public class PushBackTest {public static void main(String[] args) throws IOException{//需要指定PushbackReader的缓冲区的大小 PushbackReader pr = new PushbackReader(new FileReader("PushBackTest.java"),64); int hasRead = 0; char[] c = new char[32]; String lastContent=""; int target = 0; //read方法:当字符数组中满了的话,就返回-1 while((hasRead=pr.read(c))>0){ int targetIndex = 0; String content = new String(c,0,hasRead); if((target=(lastContent+content).indexOf("new PushbackReader"))>0){ pr.unread((lastContent+content).toCharArray()); int len = target>32?32:target; pr.read(c, 0, target); System.out.println(len); System.out.println(new String(c,0,len)); System.exit(0); }else{ lastContent = content; //System.out.println(lastContent); } }}}
5. 重定向的标准输出:
package com.huxin.io.test;import java.io.*;//使用重定向将将标准的输出定位到PrintStream这个流的上面,这样就可以向一个文件中写数据了。public class RedirectOut {public static void main(String[] args) throws IOException{ InputStreamReader fis = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(fis); String str = null; File file = new File("out.txt"); if(file.exists()){ file.createNewFile(); } //创建一个输出流 PrintStream ps = new PrintStream(new FileOutputStream("out.txt")); //将标准输出定位到这个流上 System.setOut(ps); while((str=bf.readLine())!=null){ System.out.println(str); }}}package com.huxin.io.test;import java.io.*;import java.util.Scanner;public class RedirectInTest {public static void main(String[] args) throws IOException{File file = new File("in.txt");if(!file.exists()){file.createNewFile();} //创建一个输入流FileInputStream fis = new FileInputStream("in.txt");//标准输出重新定向 System.setIn(fis); Scanner s = new Scanner(System.in); //以回车作为分隔符 s.useDelimiter("\n"); while(s.hasNext()){ System.out.println(s.next()); } }}
6. 使用虚拟机读取进程的数据
package com.huxin.io.test;import java.io.*;public class ReadFromProcess {public static void main(String[] args) { try { //返回与当前 Java 应用程序相关的运行时对象。Runtime.getRuntime()Process p = Runtime.getRuntime().exec("javac");BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));String str = null;while((str=br.readLine())!=null){System.out.println(str);}} catch (IOException e) {e.printStackTrace();}}}import java.io.IOException;import java.io.PrintStream;/* * 为什么没有向这个进程中写进一些东西呢????????????????????? */public class WriteToProcess {public static void main(String[] args) {try {//获得java程序的一个子进程Process p = Runtime.getRuntime().exec("java WriteToProcess");//PrintStream ps = new PrintStream(p.getOutputStream());ps.println("哈哈,我真的写进去了");} catch (IOException e) {e.printStackTrace();}}}package com.huxin.io.test;import java.io.*;import java.util.Scanner;//接受标准的输出,然后写到一个文件当中去。public class ReadStandard {public static void main(String[] args) {Scanner s = new Scanner(System.in);try {PrintStream ps = new PrintStream(new FileOutputStream("out.txt"));while(s.hasNext()){System.out.println();ps.print(s.next());}} catch (FileNotFoundException e) {e.printStackTrace();}}}
7.RandomAccessFile任意访问任何一个地方哦!!!!
package com.huxin.io.randomacesstest;import java.io.*;public class RandomAccessFileRead {public static void main(String[] args) {try {RandomAccessFile raf = new RandomAccessFile("RandomAccessFileRead.java","r");byte[] b = new byte[1024];int hasRead = 0;raf.seek(25);System.out.println(raf.getFilePointer());while((hasRead=raf.read(b))>0){System.out.println(new String(b,0,hasRead));}} catch (FileNotFoundException e) {e.printStackTrace();} catch(IOException ex){ex.printStackTrace();}}}package com.huxin.io.randomacesstest;import java.io.*;/* * 注意:第一:向一个不存在的文件写数据,它会自动创建的哦!! * 第二:在中间写数据,会覆盖原来的数据的,即不能实现数据的插入。 * 第三: 如果要实现数据的插入的话,还是需要缓存的机制PushbackReader */public class RandomAccessFileWrite {public static void main(String[] args) { try {RandomAccessFile rsf = new RandomAccessFile("hello.txt","rw");{//定位到最后rsf.seek(rsf.length());//rsf.write("我追加的内容\r\n".getBytes());}} catch (FileNotFoundException e) {e.printStackTrace();}catch(IOException ex){ex.printStackTrace();}}}package com.huxin.io.randomacesstest;import java.io.*;public class RandomAccessInsert {public static void main(String[] args) {Insert i = new Insert();try {i.insert("haha.txt", 4, "插入的内容\r\n");} catch (IOException e) {e.printStackTrace();}}}class Insert {public void insert(String name, int pos, String content) throws IOException{RandomAccessFile raf = new RandomAccessFile(name,"rw");raf.seek(pos);//prefix - 用于生成文件名的前缀字符串;必须至少是三字符长//suffix - 用于生成文件名的后缀字符串;可以为 null,在这种情况下,将使用后缀 ".tmp" //创建一个临时的文件File temp = File.createTempFile("temp", null);temp.deleteOnExit();FileOutputStream fos = new FileOutputStream(temp);//OutputStreamWriter osw = new OutputStreamWriter(fos);FileInputStream fis = new FileInputStream(temp);byte[] b = new byte[1024];int hasRead = 0;while((hasRead=raf.read(b))>0){fos.write(b);}raf.seek(pos);raf.write(content.getBytes());raf.write(fis.read());}}
8. 序列化记住三点:
1. 序列化的机制:第一次会序列化对象,后来只有遇到相同的对象,只会序列化编号。
2. 序列化具有递归序列化的性质,对象序列化了,那么它的变量也会跟着序列化。
3. transient的变量不会被序列化,但是会给它一个内存,并且会分配一个初始值。
9.新的io掌握四个核心的对象:
Channel : 它的map方法可以把一块映射到内存中去。(以前是面向流的处理)
Buffer : Buffer 是一个数组,一次次的在Channel中取水。Channel也可以一次映射到Buffer中。
Charset : unicode字符串转化成字节序列
Selector : 可以实现没有堵塞的。
补充: Path,Paths,Files,FileVisitor,WatchService
package com.huxin.io.test;import java.nio.CharBuffer;public class BufferTest {public static void main(String[] args) {//使用静态的方法创建一个CharBuffer的对象,里面有八个格子CharBuffer cb = CharBuffer.allocate(8);//8,0,8System.out.print(cb.capacity());System.out.print(cb.position());System.out.print(cb.limit());cb.append("a");cb.append("b");cb.append("c");System.out.print(cb.position()); //此时打印3 (0,1,2索引的位置已经被占去了)//本程序就像大老板一发怒,全部降级cb.flip(); //轻弹的意思System.out.print(cb.position()); //位置又重新回到起点System.out.print(cb.limit()); //limit的方法自动跳到position的位置System.out.print("取出一个元素"+cb.get()); //取出一个元素之后呢?System.out.print(cb.position()); //位置向后移了一格变为1System.out.print(cb.limit()); //位置又重新回到8cb.clear(); //方法表示一切重新开始并且这个方法不会清空里面元素的内容。System.out.print(cb.position()); System.out.print(cb.limit()); System.out.print("取出一个元素"+cb.get()); //根据position取数字的话,则position的位置一直向后移动System.out.print("取出一个元素"+cb.get()); System.out.print("取出一个元素"+cb.get(2)); //根据索引取数字的话,则position的位置不动System.out.print(cb.position()); }}package com.huxin.io.test;import java.io.*;import java.nio.CharBuffer;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;/* * 以块读取数据 */public class ChannelTest {public static void main(String[] args) throws IOException{ File file = new File("ChannelTest.java"); //创建一个 FileChannel类的对象 FileChannel inChannel = new FileInputStream(file).getChannel(); FileChannel outChannel = new FileOutputStream("a.txt").getChannel(); //写的话,它会自动创建哦 //通过映射读到buffer中去 MappedByteBuffer mbb = inChannel.map(FileChannel.MapMode.READ_ONLY, 0 ,file.length()); outChannel.write(mbb); //使用charset创建一个解码器 Charset charset = Charset.forName("GBK"); //创建一个解码器的对象 CharsetDecoder cd = charset.newDecoder(); CharBuffer cb = cd.decode(mbb); System.out.println(cb.toString()); }}package com.huxin.io.test;import java.io.FileOutputStream;import java.io.IOException;import java.nio.channels.FileChannel;import java.nio.channels.FileLock;public class ChannelLockTest {public static void main(String[] args) throws IOException{ FileChannel fc = new FileOutputStream("b.txt").getChannel(); FileLock fl = fc.lock(); //这样写的话,线程在这里一直堵塞。 try {Thread.sleep(10000); //在十秒内无法修改文件} catch (InterruptedException e) {e.printStackTrace();} fl.release(); //释放这把锁。}}import java.nio.*;import java.nio.charset.*;public class CharsetTransform{public static void main(String[] args)throws Exception{// 创建简体中文对应的CharsetCharset cn = Charset.forName("GBK");// 获取cn对象对应的编码器和解码器CharsetEncoder cnEncoder = cn.newEncoder();CharsetDecoder cnDecoder = cn.newDecoder();// 创建一个CharBuffer对象CharBuffer cbuff = CharBuffer.allocate(8);cbuff.put('孙');cbuff.put('悟');cbuff.put('空');cbuff.flip();// 将CharBuffer中的字符序列转换成字节序列ByteBuffer bbuff = cnEncoder.encode(cbuff);// 循环访问ByteBuffer中的每个字节for (int i = 0; i < bbuff.capacity() ; i++){System.out.print(bbuff.get(i) + " ");}// 将ByteBuffer的数据解码成字符序列System.out.println("\n" + cnDecoder.decode(bbuff));}}
自己总结的两个工具类:
package com.huxin.io.IOUtil;import java.io.*;import java.nio.file.*;import java.nio.file.attribute.*;/* * @param file * 说明:watchService.take()是主要的方法 一直读取该路径变动的事件(比如说增加一个文件夹,或者删除一个文件夹) */public class FileListener { public static void WatchFile(String file){ try{// 获取文件系统的WatchService对象WatchService watchService = FileSystems.getDefault().newWatchService();// 为C:盘根路径注册监听Paths.get(file).register(watchService , StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);while(true){// 获取下一个文件改动事件WatchKey key = watchService.take(); //在这里堵塞住了for (WatchEvent<?> event : key.pollEvents()) {System.out.println(event.context() +" 文件发生了 "+ event.kind()+ "事件!");}// 重设WatchKeyboolean valid = key.reset();// 如果重设失败,退出监听if (!valid) {break;}}} catch(Exception e){ e.printStackTrace();} }}package com.huxin.io.IOUtil;/* * 说明: 使用File工具类walkFileTree()来遍历整个目录和文件(这个程序有点问题,一直都找不出来) */import java.io.*;import java.nio.file.*;import java.nio.file.attribute.*;public class FindFile {public static void main(String[] args){// 遍历g:\publish\codes\15目录下的所有文件和子目录try {Files.walkFileTree(Paths.get("d:",""), new SimpleFileVisitor<Path>(){// 访问文件时候触发该方法@Overridepublic FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException{System.out.println("正在访问" + file + "文件");// 找到了FileInputStreamTest.java文件if (file.endsWith("FileInputStreamTest.java")){System.out.println("--已经找到目标文件--");return FileVisitResult.TERMINATE;}return FileVisitResult.CONTINUE;}//// 开始访问目录时触发该方法//@Override//public FileVisitResult preVisitDirectory(Path dir//, BasicFileAttributes attrs) throws IOException//{//System.out.println("正在访问:" + dir + " 路径");//return FileVisitResult.CONTINUE;//} });} catch (IOException e) {e.printStackTrace();} }}
- io流整体总结
- java io流总结
- IO流总结
- IO流总结
- java IO流总结
- IO流学习总结
- Java IO流总结
- IO流的总结
- java io流总结
- IO流总结之一
- java IO流总结
- JAVA io 流总结
- java IO流总结
- IO流总结
- IO流总结
- IO流总结3
- IO流总结
- IO流总结
- 贪心算法_题目1082:代理服务器
- Ctex with Beamer
- Android学习笔记---java实现多线程下载器,30_多线程下载原理介绍和使用
- secureCRT无法输入
- 黑马程序员_多线程间通信的两种方式
- IO流总结
- 虚拟机上centos设置固定IP
- Chef学习之六:Knife cookbook
- 个人写的第三方报警设备SDK接入规范书,可供奋斗在开发第一线的同志们参考.
- 分布式开源框架Hadoop介绍
- java遍历HashMap的方式
- Combination Sum II
- 设计模式案例代码之外观模式
- 解决PHP中的Fatal error: Call to undefined function curl_init()