IO的基本简单操作

(一)Java流类的类结构图

IO的流类的结构图

(二)Java的IO分类(并未完全列出)

Java中IO的常用类

(三)文件操作

递归地输出一个目录下所有文件:

import java.io.File;

public class RecursiveListAllFiles {
public static void listAllFiles(File dir)
{
    if (dir == null || !dir.exists()) {
        return;
    }
    if (dir.isFile()) {
        System.out.println(dir.getName());
        return;
    }
    for (File file : dir.listFiles()) {
        listAllFiles(file);
    }
}
public static void main(String[] args) {
    File file = new File("D:\\java");
    RecursiveListAllFiles.listAllFiles(file);
}
}

(四)字节文件处理复制

字节流可以处理所有数据类型的数据,在java中以Stream结尾;

public class CopyFileByInputStream {

public static void main(String[] args) throws IOException {
    //1 源文件
    File src = new File("E:\\人类活动识别新方法.pdf");
    //2目标文件
    File target = new File("E:\\新方法.pdf");
    //3 缓存
    byte[] b = new byte[1024];
    //4相对缓存来说是输入流
    FileInputStream in = new FileInputStream(src);
    //5 相对缓存来说是输出流
    FileOutputStream out = new FileOutputStream(target);
    //6每次的输入的长度
    int len;
    //如果长度大于0
    while((len = in.read(b))> 0) {
        out.write(b, 0, len);
    }
    in.close();
    out.close();
}

}

(五)读取字符文件和写入字符文件

字符流处理文本数据,在java中以Reader和Writer结尾;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
//读取字符文件
public class FileReaderTest
{

public static void main(String[] args) throws IOException
{
     try {
        BufferedReader bf = new BufferedReader(new FileReader("D:\\Test.txt"));
        String str;
        while((str=bf.readLine()) != null) {
            System.out.println(str);
        }
        bf.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

}

//写入字符文件
public class FileWriterTest
{
public static void main(String[] args)
{
   try {
        BufferedWriter out = new BufferedWriter(new FileWriter("D:\\Test.txt"));
        for (int i = 0; i < 1000; i++) {
            out.write("aString" + i);
            out.newLine();
            out.flush();
        }
        out.close();
    } catch (IOException e) {
    }
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值