Java文件的基本操作代码

代码:

import com.sun.beans.editors.ByteEditor;

import java.io.*;
import java.util.Scanner;

class Test
{
    private static String filename;
    private static File f;
    Test(String filename){
        this.filename=filename;
    }
    static void open(){
        f = new File(filename);
        if(f.exists()){
            //如果存在
            System.out.println("文件已经存在");
        }
        else{
            //没有该文件
            try{
                System.out.println("该文件不存在,新建文件");
                f.createNewFile();
            }
            catch (IOException e){
                System.out.println(e.getMessage());
                System.out.println("创建失败");
            }
        }
    }
    //显示文件信息
    void Show(){
        System.out.println("绝对路径"+f.getAbsoluteFile());
        System.out.println("文件名"+f.getName());
        System.out.println("路径"+f.getPath());
    }
    //遍历目录文件
    void List(String list_name){
        File f2 = new File(list_name);
        String[] all_result = f2.list();
        for(String s : all_result)
            System.out.println(s);
    }
    //删除文件
    void Delete(){
        f.delete();
    }
    //输入流
    void Input(){
        byte[] b = new byte[1024];
        int n = -1;
        try {
            FileInputStream in = new FileInputStream(f);
            while((n=in.read(b))!=-1){
                String s = new String(b);
                System.out.println(s);
            }
            in.close();
        }catch (IOException e){
            System.out.println("读取文件错误");
        }
    }
    //输出流
    void OutPut(String content){
        byte[] b = content.getBytes();
        try{
            FileOutputStream out = new FileOutputStream(f);
            out.write(b);
            out.close();
            System.out.println("文件写入成功");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //续写
    void AppendMethod(String content) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(f, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class c {
    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件名");
        String filename = sc.nextLine();
        //创建文件对象
        Test t = new Test(filename);
        t.open();
        t.Show();
        t.OutPut("Java");
        t.Input();
        t.AppendMethod("123");
        t.Input();
        t.Delete();
        t.List("C:\\");
    }
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Who_Am_I.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值