java基础--IO流-----分割文件

32 篇文章 0 订阅

分割文件
RandomAccessFile类的主要功能是完成随机读取功能,可以读取指定位置的内容。
之前的File类只是针对文件本身进行操作的,而如果要想对文件内容进行操作,则可以使用RandomAccessFile类,此类属于随机读取类,可以随机读取一个文件中指定位置的数据,
实例化此类的时候需要传递File类,告诉程序应该操作的是哪个文件,之后有一个模式,文件的打开模式,常用的两种模式:
r:读模式
w:只写
rw:读写,如果使用此模式,如果此文件不存在,则会自动创建。
public void seek(long pos) throws IOException 设置读指针的位置。

package day28;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

public class FileSplit {
    //文件的路径
    private String filePath;
    //文件的名字
    private String fileName;
    //块数
    private int size;
    //每一块的大小
    private long blockSize;
    //每一块的名称
    private List<String> blockPath;
    //文件实际大小
    private long length;

    //提供构造器
    public FileSplit(){
        blockPath = new ArrayList<>();
    }
    public FileSplit(String filePath){
        this(filePath,1024);
    }
    public FileSplit(String filePath,long blockSize){
        this();
        this.filePath=filePath;
        this.blockSize=blockSize;
        init();
    }

    //初始化操作,计算块数,确定文件名
    public void init(){
        //肯定会执行||后面的语句,此时就把路径封装成了File类的一个对象
        File src = null;
        if(filePath==null || !((src=new File(filePath)).exists())){
            return;
        }
        //如果是文件夹
        if(src.isDirectory()){
            return;
        }
        this.fileName = src.getName();
        //计算每一块的大小
        this.length = src.length();
        //如果确定的每块大小大于实际大小,即此时会分割为一块
        if(this.blockSize>length){
            blockSize=length;
        }
        //确定块数
        size = (int) Math.ceil(length*1.0/this.blockSize);

    }

    //确定分割文件的名称
    public void initPathName(String destPath){
        for(int i=0;i<size;i++){
            blockPath.add(destPath+"/"+i+".txt");
        }
    }
    /*
     * 分割文件,文件的存储目录
     * 1、第几块
     * 2、其实位置
     * 3、实际大小
     */
    public void split(String destPath){
        //确定文件路径
        initPathName(destPath);
        int beginPos = 0;//起始点
        long actualBlockSize = blockSize;//实际每一块的大小
        for(int i=0;i<size;i++){
            if(i==size-1){
                actualBlockSize = length-beginPos;
            }
            splitDetial(i,beginPos,actualBlockSize);
            beginPos+=actualBlockSize;
        }
        System.out.println("分割成功!");
    }
    //分割文件,即文件的拷贝
    public void splitDetial(int idx,long beginPos,long actualBlockSize){
        //创建源
        File src = new File(this.filePath);//源文件
        File dest = new File(this.blockPath.get(idx));//目标文件
        RandomAccessFile raf = null;
        BufferedOutputStream bos =null;
        try {
            raf = new RandomAccessFile(src,"r");
            bos = new BufferedOutputStream(new FileOutputStream(dest));
            raf.seek(beginPos);
            byte[] flush = new byte[1024]; 
            int len = 0;
            while((len=raf.read(flush))!=-1){
                if(actualBlockSize-len>=0){
                    bos.write(flush,0,len);
                    actualBlockSize -=len;
                }else{
                    bos.write(flush,0,(int)actualBlockSize);
                    break;
                }
            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                raf.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }


    public static void main(String[] args) {
        FileSplit fs = new FileSplit("E:/tesu/aaa.txt");
        System.out.println(fs.size);
        fs.split("E:/tesu");

    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中使用HttpURLConnection上传文件可以通过以下步骤实现: 1. 创建URL对象,指定上传文件的URL地址。 2. 打开HTTP连接,并设置请求方法为POST。 3. 设置HTTP请求头部信息,包括Content-Type和boundary。 4. 设置HTTP请求体信息,包括上传文件的内容和分割线。 5. 读取服务器端返回的响应信息。 示例代码如下: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void main(String[] args) throws Exception { String urlStr = "http://example.com/upload"; String filePath = "C:/test.txt"; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String boundary = "---------------------------" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream out = conn.getOutputStream(); // 写入分割线 out.write(("--" + boundary + "\r\n").getBytes()); // 写入文件名 out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath + "\"\r\n").getBytes()); // 写入文件类型 out.write(("Content-Type: application/octet-stream\r\n").getBytes()); // 写入空行 out.write(("\r\n").getBytes()); // 写入文件内容 FileInputStream fileIn = new FileInputStream(filePath); byte[] buffer = new byte[1024]; int len; while ((len = fileIn.read(buffer)) != -1) { out.write(buffer, 0, len); } fileIn.close(); // 写入空行 out.write(("\r\n").getBytes()); // 写入分割线 out.write(("--" + boundary + "--\r\n").getBytes()); out.flush(); out.close(); // 读取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } ``` 其中,filePath为需要上传的文件路径,urlStr为服务器端接收文件的URL地址。在示例代码中,我们使用了multipart/form-data类型的请求体格式,可以在请求头部信息中设置Content-Disposition、Content-Type等参数。同时,我们也设置了一个分割线boundary,用于分隔不同的请求体部分。最后,我们通过读取服务器端返回的响应信息,来获取上传文件的结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值