IO流----读取文件,复制文件,追加/插入文件

文件结构

读取文件

 第一种方式

public class Test {
    public static void main(String[] args) throws IOException {
  // 最好别用FileReader,容易漏读
// 如果是window系统,/需要换成\ FileInputStream in = new FileInputStream("/Users/mac/eclipse-workspace/Demo/src/Test/file.txt"); byte[] buffer = new byte[1024]; int len = 0; while((len=in.read(buffer))!=-1) { System.out.println(new String(buffer,0,len)); } in.close(); // 一定记得关闭! } }

 第二种方式:

public class Try {

    public static void main(String[] args) throws IOException {
        File file = new File("/Users/mac/Desktop/1.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
        while (true) {
            String line = reader.readLine();
            if(line==null) {break;}
            System.out.println(line);
        }
    }
}

 

结果

 

复制文件

/*
     * 目标:把1.txt内容复制到2.txt
     */
    File file = new File("/Users/mac/Desktop/1.txt");
    File file2 = new File("/Users/mac/Desktop/2.txt");
    @Test
    public void test1() throws IOException {
        FileInputStream in = new FileInputStream(file);
        FileOutputStream out = new FileOutputStream(file2);
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
    }

 

追加/插入文件 

追加:

https://blog.csdn.net/weixin_44001765/article/details/98196177?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-1-98196177-null-null.pc_agg_new_rank&utm_term=io流追加写入&spm=1000.2123.3001.4430

一个文件插入另一个文件:

https://zhidao.baidu.com/question/583629736414603045.html

FileInputStream和FileOutputStream的简单用法

https://blog.csdn.net/qq_43750656/article/details/118355995

 

posted @ 2022-08-19 22:14  2337  Views(91)  Comments(0Edit  收藏  举报