Java中的IO整理

创建文件

public static void createNewFile() throws IOException {
        String fileName = "D:" + File.separator + "hello.txt";
        File f = new File(fileName);
        f.createNewFile();
    }

删除文件

public static void deleteFile() {
        String fileName = "D:" + File.separator + "hello.txt";
        File f = new File(fileName);
        if (f.exists()) {
            f.delete();
        }
    }

新建文件夹

public static void createNewDir() {
        String fileName = "F:" + File.separator + "ff";
        File f = new File(fileName);
        f.mkdir();
    }

递归遍历目录

public static void traversalDir(String filePath) {
        File dir = new File(filePath);
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file != null) {
                if (file.isDirectory()) {
                    traversalDir(file.getAbsolutePath());
                } else {
                    System.out.println(file.getAbsolutePath());
                }
            }

        }
    }

写入文件

    public static void writeString2File() throws IOException {
        String filePath = "D:" + File.separator + "hello.txt";
        File f = new File(filePath);
        OutputStream out = new FileOutputStream(f, false);
        String str = "abcdefghijklmnopqs";
        byte[] bytes = str.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            out.write(bytes[i]);
        }
        out.close();
    }

读文件

    public static void readFile() throws IOException {
        String filePath = "D:" + File.separator + "hello.txt";
        File f = new File(filePath);
        InputStream in = new FileInputStream(f);
        byte[] bytes = new byte[1024];
        int temp = 0;
        int count = 0;
        while ((temp = in.read()) != -1) {
            bytes[count++] = (byte) temp;
        }
        in.close();
        System.out.println(new String(bytes));
    }

对象序列化

    public class User implements Serializable{
    private static final long serialVersionUID = 1L;
    private transient int id = 123;
    private transient String name = "abc";
    private String password = "12345";

    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public User() {

    }

    public int getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private void privateMethod() {
        System.out.println("access the private method");
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
        }
    }
    public static void serializClass() throws Exception {
        String filePath = "D:" + File.separator + "seri.txt";
        File f = new File(filePath);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
        out.writeObject(new User(123,"jim","abcde"));
        out.close();
    }

反序列化

    public static void deserializClass() throws Exception {
        String filePath = "D:" + File.separator + "seri.txt";
        File f = new File(filePath);
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
        User user = (User) in.readObject();
        in.close();
        System.out.println(user);
    }
### Java IO流使用总结 Java IO(Input/Output)流用于处理设备之间的数据传输。它主要分为字节流和字符流两大类,每种流又可以进一步划分为输入流和输出流。 #### 1. 字节流 字节流继承自`InputStream`和`OutputStream`两个抽象基类。它们以8位字节为单位进行数据读取或写入操作- **FileInputStream/FileOutputStream**: 基本的文件读写功能。 ```java try (FileOutputStream fos = new FileOutputStream("output.txt")) { fos.write("Hello, world!".getBytes()); } catch (Exception e) { e.printStackTrace(); } ``` - **DataInputStream/DataOutputStream**: 提供对基本数据类型的读写支持[^1]。 ```java try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"))) { dos.writeInt(123); dos.writeDouble(456.789); } catch (Exception e) { e.printStackTrace(); } ``` #### 2. 字符流 字符流继承自`Reader`和`Writer`两个抽象基类。它们以16位Unicode字符为单位进行数据读取或写入操作- **FileReader/FileWriter**: 文件字符读写的基础实现。 ```java try (FileWriter fw = new FileWriter("char_output.txt")) { fw.write("你好,世界!"); } catch (Exception e) { e.printStackTrace(); } ``` - **BufferedReader/BufferedWriter**: 添加缓冲机制,提高性能。 ```java try (BufferedWriter bw = new BufferedWriter(new FileWriter("buffered_output.txt"))) { bw.write("带缓冲区的写入"); } catch (Exception e) { e.printStackTrace(); } ``` #### 3. 转换流 转换流用于解决不同编码间的转换问题。 - **InputStreamReader/OutputStreamWriter**: 实现字节流与字符流之间的转换[^4]。 ```java try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("utf8_file.txt"), "UTF-8")) { osw.write("这是一个UTF-8编码的字符串"); } catch (Exception e) { e.printStackTrace(); } ``` #### 4. 序列化与反序列化 序列化是指将对象的状态保存到存储介质中;而反序列化则是指从存储介质中恢复对象状态的过程。 - **ObjectOutputStream/ObjectInputStream**: 处理对象的序列化与反序列化[^3]。 ```java // 序列化 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.ser"))) { oos.writeObject("测试字符串"); } catch (Exception e) { e.printStackTrace(); } // 反序列化 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.ser"))) { String str = (String) ois.readObject(); System.out.println(str); } catch (Exception e) { e.printStackTrace(); } ``` #### 5. 文件管理 通过`File`类可方便地管理和查询文件属性以及执行简单的目录遍历等操作[^2]。 ```java File file = new File("/path/to/somefile.txt"); if (file.exists()) { System.out.println("文件名:" + file.getName()); } ``` --- ### 总结 以上是对Java IO流的主要分类及其典型应用场景的一个概述。无论是简单的小型应用还是复杂的大型项目开发过程中,合理选用合适的IO方式能够显著提升程序效率并简化代码逻辑结构设计。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值