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();
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容

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