java之字节流读写文件

1、实现字节流对文件数据的读取

package com.company;
import java.io.*;
import java.util.*;
public class test {
    public static void main(String[] args) throws IOException {
        FileInputStream ins =new FileInputStream("testfile.txt的具体路径");
        int b=0;
        while((b=ins.read())!=-1){
            System.out.print((char)b);
        }
        ins.close();
    }
}

或者

package com.company;
import java.io.*;
import java.util.*;
public class test {
    public static void main(String[] args) throws IOException {
        Scanner input =new Scanner(System.in);
        InputStream in=null;
        try {
            String str = input.next().toString();  //文件名
            in = new FileInputStream(根目录+str);
            int n;
            while ((n = in.read()) != -1) { // 读取文件
                System.out.println((char) n);
            }
        }finally {  // 如果输入为空,关闭流
            if(in !=null)
                in.close();
        }
    }
}

代码中的testfile里面内容是:hello
运行结果:
在这里插入图片描述2、实现字节输出流将数据写入文件

package com.company;
import java.io.*;
import java.util.*;
public class test {
    public static void main(String[] args) throws IOException {
        Scanner input =new Scanner(System.in);
        FileOutputStream ous =new FileOutputStream("testfile2");
        String str =input.next().toString();
        ous.write(str.getBytes());
        ous.close();
    }
}

运行后,新建的文件可能不会立即显示,这时候可以通过刷新,显示出新建的文件。
(刷新操作:file->Invalidate Caches / Restart…)

运行结果:输入要存入文件的内容:hellol
在这里插入图片描述在这里插入图片描述3、综合应用:使用字节输出流和输入流,把给定文件里的内容复制到另一个给定文件中。

接收给定的一行字符串(如:/test1/d.txt /test1/e.txt。其中第一个路径为源文件路径,第二个路径为目标文件路径);
使用字节输出流和输入流,把第一个文件里的内容复制到第二个文件中。
import java.io.*;
import java.util.Scanner;

public class FileTest {
    public static void main(String[] args) throws IOException {
     
        // 使用字节输出流和输入流,把给定文件里的内容复制到另一个给定文件中
        Scanner input =new Scanner(System.in);
        String str1 =input.next().toString();
        String str2 =input.next().toString();
        FileInputStream ins =new FileInputStream(str1);
        FileOutputStream ous =new FileOutputStream(str2);
        int b=0;
        while((b=ins.read())!=-1){
            ous.write(b);
        }
        ins.close();
        ous.close();
        
       
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值