Java文件读写及上传下载

Java对文件读写操作算是常用的操作,使用JavaIO较多,JavaIO提供的方式也很多,包括字节流、字符流。

本文使用缓冲字符流BufferedReader和BufferedWriter进行文件的读写。

1.读

//读文件
public String read(String fileName){
    File file = new File(filename);
    if(null != file && file.exists() && file.length() != 0L){
        try{
            String encoding = "utf-8";
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file),encoding);
            BufferedReader bfr = new BufferedREader(isr);
            String txt = bfr.readLine();
            String context = "";
            while(txt != null){
                context = context + txt;
                txt = bfr.readLine();
            }
            bfr.close();
            return context;
    }catch(IOException e){
        e.printStackTrace();
    }
    return "error!";
}

2.写

//写文件
public Boolean write(String filename, String txt){
    try{
        //文件内容全替换
        BufferedWriter bfw = new BufferedWriter(new FileWriter(filename));
        //文件内容末尾追加
        BufferedWriter bfw = new BufferedWriter(new FileWriter(filename,true));
        bfw.write(txt);
        bfw.flush();
        bfw.close();
        return true;
    }catch(IOException e){
        e.printStackTrace();
    }
    return false;
}

3.文件上传及下载

还可以通过SCPClient进行文件的上传和下载

Connection conn = new Connection("127.0.0.1");//使用服务器IP
try{
    conn.connect();
    conn.authenticateWithPassword("user","password");
    SCPClient sc = new SCPClient(conn);
    //下载至本地d盘
    sc/get("/home/test.txt","d/");
    //上传本地d盘文件至服务器
    sc.put("d:/test2.txt","/home/");
}catch(IOException){
    e.printStackTrace();
}

较为高级的操作是通过HttpServletRequest和HttpServletResponse进行文件的上传下载操作。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值