Java-文件输入输出(字节流)

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class fiIenOuputStreamDemo {
    public static void main(String[] args) {
        //读文件从文件(或键盘,网络)
        try {//所有**非RuntimeException类及其子类**的编译时异常都要抓异常
            //E:\\a.txt是文件的位置,java中"\\"或"/"代表"\"
            FileInputStream in=new FileInputStream("E:/a.txt");//new一个对象代表E:\\a.txt文件,对in的操作,就是对文件的操作
            int v=-1;
            while((v=in.read())!=-1){//读文件
                System.out.print((char)v);
            }
        in.close();//关闭文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        //写文件到文件(或显示器,打印机,网络)
        String str="sfdghdgh2653";
        try {
            FileOutputStream out=new FileOutputStream("E:\\b.txt");
            byte buf[]=str.getBytes();//返回str数组
            out.write(buf);//把数组buf写入文件E:\\b.txt
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ACM中的scanner类也可以读文件

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class scannerDemo {


    public static void main(String[] args) {
        Scanner sc;
        try {
            sc = new Scanner(new FileInputStream("G:\\a.txt"));
            while(sc.hasNext()){
                String str=sc.next();
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值