IO

来源:互联网 发布:php一句话图片木马 编辑:程序博客网 时间:2024/06/10 09:01

1    Io用法

 

       File类是IO包中唯一代表磁盘文件本身的信息类,而不是文件中的内容。File类定义了一些与平台无关的方法来操纵文件,例如:创建 删除文件 和重命名文件。

举例说明:判断某个文件是否存在,存在则删除,不存在则创建

package com.TextFile;

 

import java.io.File;

 

public class FileText {

 

    /**

     * @param args

     */

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

       // TODO Auto-generated method stub

 

       File f=new File("1.txt");

       if(f.exists()){

           f.delete();

       }else{

           f.createNewFile();

       }

       System.out.println("File name:"+f.getName());

System.out.println("File path:"+f.getPath());

       System.out.println("File abs path:"+f.getAbsolutePath());

       System.out.println(f.exists()?"exist":"not exist");

       System.out.println("File name:"+f.getName());

    }

}

 

RandomAccessFile   优势 随机读写等长记录格式的文件 ,只能够访问文件。带有很多方法。

 

流分成两大类    节点流和处理流

 

   流是字节的抽象

 

inputStream 常用方法

 

        int read() skip(long n)  available()  mark(int readlimit) reset() 他们一起使用为什么要调用close方法,因为系统产生了一个系统流资源,而java程序产生了一个实例,垃圾回收器只能收回自己产生的没有用的实例,所以调用close方法就是关闭系统的流资源。outputStream 抽象类 常见的方法:write(int b) write(byte[] b) write(byte[] b,int off,int len)  void flush()void close() 

 

FileInputStream FileOutputStream

 

2   了解常用的构造方法   下面是简单的举例:

 

package IO;

 

 

 

import java.io.*;

 

public class Demon11 {

    /**

 

     * @param args

 

     */

 

    public static void main(String[] args) {

 

       // TODO Auto-generated method stub

 

       try {

 

           FileOutputStream fos = new FileOutputStream("aa.txt");

 

           fos.write("hongjiang".getBytes());

 

           byte[] a = new byte[1024];

 

           FileInputStream fis = new FileInputStream("aa.txt");

 

           int len = fis.read(a);

 

           System.out.println(new String(a, 0, len - 1));

 

       } catch (FileNotFoundException e) {

 

           // TODO Auto-generated catch block

 

           System.out.println("创建文件失败");

 

       } catch (IOException e) {

 

           // TODO Auto-generated catch block

 

           e.printStackTrace();

 

       }

 

    }

 

 

 

}

 

3   Reader writer 是用于读写字符的,上面是用于读写字节的  字符和字节要区分

 

 

注意FileWriterclose()的配合调用  FileOutputStream 里面的Writer()方法自带了flash()方法,而FileWriter不带flash()方法,必须写close()方法,否则不能写到文件中去,而写到内存中去了。

 

PipedInputStream PipedOutputStream 类是用于线程之间的通信。字节

 

PipedReader PipedWriter 同样使用public void connect(PipedOutputStream src) 连接方法ByteArrayInputStream ByteArrayOutStream   在上面的例子中用到了字符转换成自己,String.getByte(),把字节转换成字符newString(byte[],0,length

 

 

原创粉丝点击