java io

java io主要有5个核心类和一个核心接口:

五个核心类:File、InputStream、OutputStream、Reader、Writer;
一个核心接口: Serializable
File类是唯一一个与文件本身操作相关的类(创建、删除);

File类

构造方法:

public File(String pathname) { //设置完整路径
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

   public File(String parent, String child) {// 设置父路径和子路径
        if (child == null) {
            throw new NullPointerException();
        }
        if (parent != null) {
            if (parent.equals("")) {
                this.path = fs.resolve(fs.getDefaultParent(),
                                       fs.normalize(child));
            } else {
                this.path = fs.resolve(fs.normalize(parent),
                                       fs.normalize(child));
            }
        } else {
            this.path = fs.normalize(child);
        }
        this.prefixLength = fs.prefixLength(this.path);
    }

创建文件:

    public boolean createNewFile() throws IOException {
        SecurityManager security = System.getSecurityManager();
        if (security != null) security.checkWrite(path);
        if (isInvalid()) {
            throw new IOException("Invalid file path");
        }
        return fs.createFileExclusively(path);
    }

public boolean delete() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkDelete(path);
        }
        if (isInvalid()) {
            return false;
        }
        return fs.delete(this);
    }

public boolean delete() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkDelete(path);
        }
        if (isInvalid()) {
            return false;
        }
        return fs.delete(this);
    }


package just;

import java.io.File;
import java.io.IOException;

public class StringBase{
    public static void main(String args[]) throws IOException{
        File myFile =new File("D:"+File.separator+"Life"+File.separator+"Test.txt");
 /*文件不能重名、重复、父目录要存在,路径的分隔符为“\\”;
        最合理的路径创建为:
        file.separator,(其实若有父路径要判断是否存在父路径)
        */
        if(myFile.createNewFile())
            System.out.println("创建OK");
        else
            System.out.println("创建NG");
        if(myFile.exists()){
            System.out.println("执行删除");
            myFile.delete();
            System.out.println("删除OK");
        }
        else{
            System.out.println("创建"+myFile.createNewFile());
        }
    }
}

父路径

   public String getParent() {
        int index = path.lastIndexOf(separatorChar);
        if (index < prefixLength) {
            if ((prefixLength > 0) && (path.length() > prefixLength))
                return path.substring(0, prefixLength);
            return null;
        }
        return path.substring(0, index);
    }
   public boolean mkdir() { 创建1级文件夹
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
        }
        if (isInvalid()) { 
            return false;
        }
        return fs.createDirectory(this);
    }
    public boolean mkdirs() { 创建多级文件夹
        if (exists()) {
            return false;
        }
        if (mkdir()) {
            return true;
        }
        File canonFile = null;
        try {
            canonFile = getCanonicalFile();
        } catch (IOException e) {
            return false;
        }

        File parent = canonFile.getParentFile();
        return (parent != null && (parent.mkdirs() || parent.exists()) &&
                canonFile.mkdir());
    }

File类的文件属性
包含文件的属性信息,如建立时间,修改时间等;


操作文件的输入输出,采用字节流和字符流;

字节流\字符流

字节流:InputStream\OutPutStream;
字符流:reader/writer

字节流
OutputStream类:

public abstract class OutputStream implements Closeable, Flushable{
         public void flush() throws IOException {
    }
    public void close() throws IOException {
    }
}
//实现了两个接口

public interface Closeable extends AutoCloseable {
       public void close() throws IOException;
       ...
}

public interface AutoCloseable {
   void close() throws Exception;
} //自动关闭接口

public interface Flushable {

   
    void flush() throws IOException; //请空
}

public abstract void write(int b) throws IOException;//输出单个字节数组 
 public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }
    public void write(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
                   ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        for (int i = 0 ; i < len ; i++) {
            write(b[off + i]);
        }
    }
package StringBase;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;


public class Base {


    public static void main(String args[]) throws Exception {
        File file=new File("D:"+File.separator+"Life"+File.separator+"Test.txt");
        if(!file.getParentFile().exists())
            file.getParentFile().mkdirs();//判断是否存在目录
        OutputStream output=new FileOutputStream(file,true);
        //true 代表追加,不写代表覆盖
        String str="dream"+"\\r";
        byte[] b=str.getBytes();\\字符串转化为字节数组
        output.write(b,1,3);//输出后会覆盖
        output.close();//关闭




    }
}

InputStream

  public abstract int read() throws IOException;
  public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }
  public abstract int read() throws IOException;
 public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }
package StringBase;
import java.io.*;



public class Base {


    public static void main(String args[]) throws Exception {
        File file=new File("D:"+File.separator+"Life"+File.separator+"Test.txt");
        if(file.exists())
        {
            InputStream input=new FileInputStream(file);
            int temp=0;
            while ((temp=input.read())!=-1){
                System.out.println((char)(temp));
            }
            input.close();
        }

    }
}

字符流

package StringBase;
import java.io.*;



public class Base {


    public static void main(String args[]) throws Exception {
        File file=new File("D:"+File.separator+"Life"+File.separator+"Test.txt");
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        Writer out=new FileWriter(file);
        String str="hello world";
        out.write(str);
        out.flush();
        //out.close();
    }
}

package StringBase;
import java.io.*;



public class Base {


    public static void main(String args[]) throws Exception {
        File file=new File("D:"+File.separator+"Life"+File.separator+"Test.txt");
        if(file.exists())
        {
          Reader in=new FileReader(file);
          int temp=0;
          while ((temp=in.read())!=-1){
            System.out.println((char)temp);
        }

        }

    }
}

字节流和字符流
1、字节流可以直接与终端交流,而字符流通过缓冲区与终端进行交互;
2、字符流不使用关闭功能时(close()),其不会强制把缓冲区的数据清空,即数据不会写入到文件中去,除非采用flush()方法;
3、字节数据处理使用较多,比如图片,音乐电影;字符流数据处理中文时较为方便;

转换流
字符流需要缓冲区,但是字符流可以直接输出字符串,故需要将字节流转换为字符流;

public class InputStreamReader extends Reader {...}
public class OutputStreamWriter extends Writer {...)

package StringBase;
import java.io.*;



public class Base {


    public static void main(String args[]) throws Exception {
        File file=new File("D:"+File.separator+"Life"+File.separator+"Test.txt");
        if(!file.getParentFile().exists())
            file.getParentFile().mkdirs();

        OutputStream output =new FileOutputStream(file);
        Writer out=new OutputStreamWriter(output);
        out.write("hello world");
        out.close();
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Java IO整理 参考文献一:http://www.cnblogs.com/lich/tag/java%20IO...
    数独题阅读 3,596评论 0 0
  • 字节流 InputStream 输入字节流 OutputStream 输出字节流 输入字节流----InputSt...
    向日花开阅读 7,061评论 0 4
  • 标准输入输出,文件的操作,网络上的数据流,字符串流,对象流,zip文件流等等,java中将输入输出抽象称为流,就好...
    navy_legend阅读 4,082评论 0 0
  • 一、IO流整体结构图 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称...
    慕凌峰阅读 5,211评论 0 12
  • 虽然写了一些javaIo流的总结,感觉依旧没有系统的了解javaIO,幸好从网上看到这一篇文章,觉得不错。整理记录...
    Marlon666阅读 2,833评论 0 2

友情链接更多精彩内容