【DemoFileOutputStream- 使用FileOutputStream写入指定内容到指定文件】

本文介绍了一个Java程序,使用FileOutputStream向指定文件写入用户输入的内容,并在操作过程中处理可能出现的文件不存在、非文件等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用FileOutputStream写入指定内容到指定文件

/**
 * @author 南风知我意唔
 * @version 1.0
 * 使用FileOutputStream写入指定内容到指定文件
 */
public class DemoFileOutputStream {
    public static void main(String[] args) {
        
        while (true){
            Scanner input=new Scanner(System.in);
            //指定文件地址
            System.out.print("FilePath:");
            String filePath=input.nextLine();
            //内容
            System.out.print("Content:");
            String message=input.nextLine();
            boolean b = false;
            try{
                b=writeToLocalFile(message, filePath, true);
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
            if (b){
                System.out.println("success!");
            }else{
                System.out.println("fail!");
            }
            System.out.print("是否继续(y)添加:");
            String y=input.nextLine();
            if (!y.equals("y")){
                System.out.println("系统退出....");
                break;
            }
        }
    }

    public static boolean writeToLocalFile(String message,String filePath,boolean b){
        File file=new File(filePath);
        System.out.println(file);
        System.out.println(filePath);
        if (message==null){
            throw new MessageIsNull("写入信息为null");
        }
        if (!file.exists()){
            throw new FileException("路径不存在:"+filePath);
        }
        if (!file.isFile()){
            throw new FileException("Not is File:"+filePath);
        }
        FileOutputStream fileOutputStream=null;
        try {
           fileOutputStream=new FileOutputStream(file,b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] messages = message.getBytes();
        try {
            fileOutputStream.write(messages);
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            if (fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
}
class FileException extends RuntimeException{
    public FileException(String message) {
        super(message);
    }
}
class MessageIsNull extends RuntimeException{
    public MessageIsNull(String message) {
        super(message);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南风知我意唔

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

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

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

打赏作者

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

抵扣说明:

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

余额充值