实训作业---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();
                }
              }
            }

posted on 2019-06-12 11:25  周橙梓  阅读(116)  评论(0编辑  收藏  举报

导航