栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

在java中,如果需要从文件中读取数据(java读取文件,并且输出文件内容)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在java中,如果需要从文件中读取数据(java读取文件,并且输出文件内容)

import java.io.*;
import java.util.Scanner;

public class 文件复制 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要复制的文件(绝对路径)");
        String srcPath=scanner.next();
        File file=new File(srcPath);
        if(!file.isFile()){
            System.out.println("错误");
            return;
        }
        System.out.println("请输入要复制到的目标路径:绝对路径");
        String destPath=scanner.next();
        File destFile=new File(destPath);
        if(destFile.exists()){
            System.out.println("目标路径的文件已经存在");
            return;
        }
        if(!destFile.getParentFile().exists()){
            System.out.println("目标的父亲目录不存在");
            return;
        }
        try (InputStream inputStream=new FileInputStream(srcPath);
        OutputStream outputStream=new FileOutputStream(destFile)){
            while (true){
                byte[]bytes=new byte[1024];
                int len =inputStream.read();
                if(len==-1){
                    break;
                }
                outputStream.write(bytes,0,len);//由于字节数可能不足1024,但是系统有可能将其填满导致拿到一些无用的数据,
                //因此设置起始位置和终止位置
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("复制完成");
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/775287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号