Java 输入和输出处理

File文件操作

File类的常用方法
方法名称说明
boolean exists( )判断文件或目录是否存在
boolean isFile( )判断是否是文件
boolean isDirectory( )判断是否是目录
String getPath( )返回此对象表示的文件的相对路径名
String getAbsolutePath( )返回此对象表示的文件的绝对路径名
String getName( )返回此对象表示的文件或目录的名称
boolean delete( )删除此对象指定的文件或目录
boolean createNewFile( )创建名称的空文件,不创建文件夹
long length()返回文件的长度,单位为字节**,** 如果文件不存在,则返回 0L
public static void main(String[] args) {
        //绝对路径  相对路径
        File file = new File("1.text");
        System.out.println("判断文件或目录是否存在:"+file.exists());
        System.out.println("判断是否是文件:"+file.isFile());
        System.out.println("判断是否是目录:"+file.isDirectory());
        System.out.println("获得相对路径:"+file.getPath());
        System.out.println("获得绝对路径:"+file.getAbsolutePath());
        System.out.println("获得文件或目录名称:"+file.getName());
        System.out.println("获得文件长度,字节数:"+file.length());
        System.out.println("删除文件或目录:"+file.delete());
        /**
         *  1 B字节 = 8 bit(位)
         *  1 KB千字节 = 1024 B
         */
        String path = "P:\\4021/001";
        String name = "1.text";
        
        try {
            File file1 = new File(path);
            if (!file1.exists()&&!file1.isDirectory()){
                //进来创建
                System.out.println("创建目录");
                file1.mkdirs();//创建多级目录 file1.mkdir(); //创建文件夹||目录
            }
            File file2 = new File(path,name);
            if (!file2.exists()&&!file2.isFile()){
                //进来创建
                boolean b = file2.createNewFile();//创建文件
                System.out.println("创建文件:"+b);
            }
        }catch (IOException e){
            e.printStackTrace();
        }

流的分类与使用

流是一组有序的数据序列

以先进先出方式发送信息的通道

Java流的分类

输入输出流是相对于计算机内存来说的

字节流是 8 位通用字节流,字符流是 16 位 Unicode 字符流

FileInputStream

InputStream类常用方法

int read( )

int read(byte[] b)

int read(byte[] b,int off,int len)

void close( )

int available():可以从输入流中读取的字节数目

子类FileInputStream常用的构造方法

FileInputStream(File file)

FileInputStream(String name)

FileOutputStream

OutputStream类常用方法

void write(int c)

void write(byte[] buf)

void write(byte[] b,int off,int len)

void close()

void flush():强制把缓冲区的数据写到输出流中

子类FileOutputStream常用的构造方法

FileOutputStream (File file)

FileOutputStream(String name)

FileOutputStream(String name,boolean append)

字节流:byte

输入流:input(读取)

InputString-->FileInputString(路径)

.available( ):获得文件字节数量

.read(字节数组)||.read( ) 读取文件内容

is.close( ); //关闭流 释放资源

/**
 * 输入流  input   读取文件内容    文件->代码
 */
public static void main(String[] args) {
        InputStream is = null;
        try {
            //创建流
            is = new FileInputStream("2.text");
            //创建字节数组    用于储存文件信息
            byte b[] = new byte[is.available()];
            is.read(b);
            
            //将字节数组  转换为字符串
            String str = new String(b,"UTF-8");
            System.out.println(str);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
                try {
                    if (is!=null)is.close();//关闭流   释放资源
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
        }

输出流:Output(写入)

OutputString -> FileOutputString("路径",boolean是否追加)

os.write(字符串.getBytes("utf-8")); 写入内容 将字符串转换为字节数组 并释放资源

os.close( ); //释放资源

os.flush( ); //强制把缓冲区的数据写到输出流中

/**
 * 输出流  output 写入   代码->文件
 */
    public static void main(String[] args) {
        try {
            //创建流
            OutputStream os = new FileOutputStream("2.txt",true);
            os.write("忘食地".getBytes("UTF-8"));
            os.close();//释放资源
        }catch (Exception e){
            e.printStackTrace();
        }
    }

字符流:char

输入流:Reader

Reader -> InputStreamReader(字节流InputString,编码) ->FileReader(路径)

解决乱码问题Reader a = new InputStreamReader(new FileputStream(路径),"utf-8");

缓冲区 BufferedReader(Reader)

br.readLine();

/**
 *读取文件内容    输入流
 */
public static void main(String[] args) {
        try{
            //Reader reader = new FileReader("2.txt");
            //解决中文乱码问题
            Reader reader = new InputStreamReader(
                    new FileInputStream("2.txt"),"utf-8");
            //字符数组
            char c[] = new char[100];
            reader.read(c);
            //将数组转换为字符串
            String msg = new String(c);
            System.out.println(msg);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
​
​
/**
 * 读取文件内容   输入流    缓冲区
 */
  public static void main(String[] args) {
        try {
            //Reader reader = new FileReader("2.txt");
            //解决中文乱码问题
            Reader reader = new InputStreamReader(
                    new FileInputStream("2.txt"),"utf-8");
            //创建缓冲区
            BufferedReader rb = new BufferedReader(reader);
​
            String line = null;
            while ((line = rb.readLine())!=null){
                System.out.println(line);
            }
            rb.close();
            reader.close();
​
        }catch (Exception e){
            e.printStackTrace();
        }
    }

输出流:Write

Write ->OutputStreamWrite(字节流OutputStream,编码) ->FileWrite(路径||file对象)

方法:

write(字符串)写入内容

flush()将缓冲区中的数据 刷新到文件中

close()释放资源

缓冲区BufferedWriter(Writer)

append(字符)写入内容

write(字符串)写入内容

flush()将缓冲区中的数据 刷新到文件中

close()释放资源

bw.newLine();//另起一行

 /**
     * 输出流  写入  字符流
     */
    public static void main(String[] args) {
        try {
            //Writer writer = new FileWriter("2.txt");
            //解决乱码
            Writer writer = new OutputStreamWriter(new FileOutputStream(
                    "2.txt",true),"utf-8");
            writer.write("xxx");
            //write.append("");
​
            System.out.println("写入成功!!");
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
​
​
 /**
     * 输出流  写入  字符流 缓冲区
     */
    public static void main(String[] args) {
        try {
            //Writer writer = new FileWriter("2.txt");
            //解决乱码
            Writer writer = new OutputStreamWriter(new FileOutputStream(
                    "2.txt",true),"utf-8");
​
            //创建缓冲区
            BufferedWriter bw = new BufferedWriter(writer);
            bw.newLine();//另起一行
            bw.append("xxx");
​
            //将缓冲区中的数据  刷新到文件中
            bw.flush();
            System.out.println("写入成功!!");
            //释放资源
            bw.close();
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

序列化与反序列化

序列化:内存对象-->文件 写入文件

ObjectOutputStream(OutputStream字节流)

writeObject(对象)

反序列化:文件-->内存对象 读取文件

ObjectInputStream(InputStream字节流)

readObject() 返回对象

注意:序列化对象要实现接口java.io.Serializable

/**
     * 序列化  写入
     * 反序列化 读取
     * @param args
     */
    public static void main(String[] args) {
        OutputStream os = null;
        ObjectOutputStream oos = null;
        InputStream is = null;
        ObjectInputStream ois = null;
        try {
            //创建字节流对象
            os = new FileOutputStream("3.txt");
            //创建序列化对象
            oos = new ObjectOutputStream(os);
            List<Dog> list = new ArrayList<Dog>();
            //让对象   可序列化
            list.add(new Dog("张三","萨摩耶"));
            //让对象   可序列化
            list.add(new Dog("李四","xxxx"));
            oos.writeObject(list);
​
            //创建字节流对象
            is = new FileInputStream("3.txt");
            //创建反序列化对象
            ois = new ObjectInputStream(is);//读取
            
            //Dog d = (Dog)ois.readObject();//读取
            //System.out.println(d.toString());
            List<Dog> dogs = (List<Dog>) ois.readObject();
            for (Dog d: dogs){
                System.out.println(d.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                os.close();
                ois.close();
                is.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
public class Dog implements java.io.Serializable{
    public  String name;
    public  String type;
​
    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", type='" + type + '\'' +
                '}';
    }
​
    public Dog(String name, String type) {
        this.name = name;
        this.type = type;
    }
}
  • 37
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值