Java

Java21-6 IO技术练习2

2019-02-02  本文已影响0人  第二套广播体操

分割文件 并写入配置文件

public class Test3 {
    public static void main(String[] args) throws IOException {

        PartFile();
    }

    private static void PartFile() throws IOException {
        File file=new File("D:\\IO\\LOVIN'YOU.mp3");
        FileInputStream fis=new FileInputStream(file);
        File destDir=new File("D:\\IO\\PART");
       if (!file.exists())
//           如果源文件不存在抛出绝对路径和异常
           throw new RuntimeException(file.getAbsolutePath()+"源文件不存在");
        if (!destDir.exists())
            destDir.mkdirs();

        FileOutputStream fos=null;
        int len=0;
        byte[] bytes=new byte[1024*1024];//1M
        int count=0;
        while ((len=fis.read(bytes))!=-1)
//            创建输出流 并明确要写入的对象
        {
            File file1=new File(destDir,(++count) + ".part");
            fos = new FileOutputStream(file1);
            fos.write(bytes, 0, len);
            fos.close();
        }
//        应该在产生碎片文件时应产生配置文件
        Properties properties=new Properties();
        File file1=new File(destDir,(++count) + ".properties");
        FileOutputStream fos1=new FileOutputStream(file1);
        properties.setProperty("partcount", String.valueOf(count));
        properties.setProperty("filename",file.getName());
        properties.store(fos1,"save part info");
        fis.close();
    }

}


按字节数截取一个字符串 abc你好 如果截到半个中文 舍弃
字符串--->字节数组 编码
字节数组--->字符串 解码 UTF-8

思路:1.示告诉我中文两个字节都是负数
2.判断截取的最后一个字节是否为负数
如果不是 直接截取
如果是 就往前判断 是否是负数 记录负数个数 如果负数个数为奇数个则舍弃最后一个

public class Test4 {
    public static void main(String[] args) throws UnsupportedEncodingException {


        String string="abc你好";
        byte[] bytes=string.getBytes("UTF-8");

        for (int x = 0; x<bytes.length ; x++) {
            String s=  partByString(string,x+1);
            System.out.println(s);
        }
    }

    private static String partByString(String s,int len) throws UnsupportedEncodingException {
//        1.将字符串转化成字节数组 判断截取的字节是否为负数
        byte[] bytes=s.getBytes("UTF-8");
        int count=0;
//      遍历数组 应该从最后一个字节开始判断并往回判断
        for (int i = len-1; i >=0; i--) {
            if (bytes[i]<0)
            {count++;}
            else{
                break;
            }
        }
        if (count%3==0)
            return new String(bytes,0,len);
           else {
               if (count%3==1)
            return new String(bytes, 0, len - 1);
               else return new String(bytes, 0, len - 2);
        }
//        定义计数器 记录负数个数 遍历中只要是负数就计数
//        判断负数个数是否为 奇数 奇数舍区最后字节 并将字节数组转换成字符串
    }
}
上一篇下一篇

猜你喜欢

热点阅读