Java 文件读取与写入

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;

public class Demo01 {
    
    
    public static void main(String[] args) throws Exception{
    
    

        String text = "Java是最好的语言!";
        File file =new File("javaio.txt");
        //如果文件不存在则创建文件
        if(!file.exists()){
    
    
            file.createNewFile();
        }
        
        //获取要被写入内容的文件(将内容写入文件)
        //如果构造方法的第二个参数为true,则新内容会添加到旧内容之后
        //						为false,或者不写第二个参数,则原文件内容会被替换
        FileWriter writer = new FileWriter(file.getName()/*,true*/);
        //将文本写入文件
        writer.write(text);
        //关闭文件写入对象
        writer.close();
        
        //创建文件输入字节流对象(获取文件内容)
        InputStream is = new FileInputStream(file);
        //获取当前可读的字节数
        int al = is.available();
        //创建字节数组,用于存放读取的文件内容
        byte[] bytes = new byte[al];
        //读取内容存到byte数组中,并返回实际读取成功的字节数
        int read = is.read(bytes);
        //将字节数组转换为字符串
        String str = new String(bytes);
        //关闭输入流对象
        is.close();
        
        //输出执行结果
        System.out.print(file.getName() + "大小为:" + read + "字节,内容为:\n" + str + "");

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44580492/article/details/112758386
今日推荐