实训作业---I/O流

1. 文件输出流的应用。

定义如下字符串:

String str = “12345abcdef@#%&*软件工程”;

编写程序将该字符串写入文件”data.txt”。

package test;
import java.io.*;
public class test1 {


    public static void main(String[] args)throws IOException {
        
        String str = "12345abcdef@#%&*软件工程";
        File file = new File("data.txt");
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(str);
        System.out.println("文件或目录是否存在:" + file.exists());
        System.out.println("是文件吗:" + file.isFile());
        System.out.println("是目录吗:" + file.isDirectory());
        System.out.println("名称:" + file.getName());
        System.out.println("绝对路径:" + file.getAbsolutePath());
        System.out.println("文件大小:" + file.length());

        bw.close();     
        fw.close();      
    }

}

 

2. 文件输入流的应用。

修改第1题中的程序,读文件”data.txt”,将读到的数据输出在控制台。

package test;
import java.io.*;
public class test2 {

    public static void main(String[] args) {
                try {
                  File file = new File("data.txt");  //创建文件对象
                  FileInputStream fis = new FileInputStream(file);
                  //根据文件的字节长度创建字节数组
                  byte[] buf = new byte[(int)(file.length())];
                  fis.read(buf);  //读取文件中的数据存放到字节数组中
                  String str = new String(buf);  //利用字节数组创建字符串
                  System.out.println(str);   //打印字符串
                  fis.close();     //关闭流
                } catch (FileNotFoundException fnfe) {
                  System.out.println("文件打开失败。");
                } catch (IOException ioe) {
                  ioe.printStackTrace();
                }
              }
            }

转载于:https://www.cnblogs.com/zhouchengzi/p/11008296.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值