美文网首页
文件的编码,文件传输基础-Java IO流

文件的编码,文件传输基础-Java IO流

作者: twoapes | 来源:发表于2018-10-17 10:52 被阅读45次

Java IO流

编码问题

  • gbk编码,英文占1个字节,中文占2个字节
  • utf-8编码,英文占1个字节,中文占3个字节
  • java是双字节编码,utf-16be编码,中文和英文都是2个字节
import java.io.UnsupportedEncodingException;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:字符集占用
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(getBytesLength("中文", "我", "gbk"));
        System.out.println(getBytesLength("英文", "a", "gbk"));
        System.out.println(getBytesLength("中文", "我", "utf-8"));
        System.out.println(getBytesLength("英文", "a", "utf-8"));
        System.out.println(getBytesLength("中文", "我", "utf-16be"));
        System.out.println(getBytesLength("英文", "a", "utf-16be"));
    }

    /**
     * @param language 语言
     * @param str      字符串
     * @param encode   编码
     * @return 编码长度结果
     */
    private static String getBytesLength(String language, String str, String encode) {
        String string = "";
        try {
            byte[] bytes = str.getBytes(encode);
            string = "在" + language + "中," + encode + "占" + bytes.length + "个字节";
            return string;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return string;
        }
    }
}

如果字节序列使用某种编码,那么把字节序列转换为字符串,那么也要使用这种编码方式,否则会出现乱码
文本文件就是字节序列,可以是任意编码的字节序列,如果在电脑上直接创建文本文件,那么该文件默认ansi编码

File类的使用

java.io.File类用于表示文件(目录)
File类只用于表示文件(目录)的信息(名称,大小等),不能用于文件内容的访问

import java.io.File;
import java.io.IOException;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:File类的使用
 */
public class Test {
    public static void main(String[] args) {
        File file = new File("D:\\log4j", "test.txt");
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("删除文件成功");
            } else {
                System.out.println("删除文件失败");
            }
        } else {
            try {
                boolean isFile = file.createNewFile();
                if (isFile) {
                    System.out.println("创建文件成功");
                } else {
                    System.out.println("创建文件失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(file);
        System.out.println(file.getAbsoluteFile());
        System.out.println(file.getPath());
        System.out.println(file.getName());
        System.out.println(file.getParentFile());
        File file2 = new File("D:\\log4j\\test");
        if (file2.isDirectory()) {
            if (file.delete()) {
                System.out.println("删除目录成功");
            } else {
                System.out.println("删除目录失败");
            }
        } else {
            if (file.mkdir()) {//单个目录,如果需要多级目录,使用mkdirs
                System.out.println("创建目录成功");
            } else {
                System.out.println("创建目录失败");
            }
        }
        System.out.println(file2);
        System.out.println(file2.getAbsoluteFile());
        System.out.println(file2.getPath());
        System.out.println(file2.getName());
        System.out.println(file2.getParentFile());
    }
}

遍历目录

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:遍历子目录和文件
 */
public class Test {
    public static void main(String[] args) {
        File file = new File("D:\\log4j");
        filesList = new ArrayList<>();
        directoryList = new ArrayList<>();
        getList(file);
        System.out.println("----------------以下是文件----------------");
        for (File file1 : filesList) {//遍历所有文件
            System.out.println(file1.getPath());
        }
        System.out.println("----------------以下是子目录----------------");
        for (File file1 : directoryList) {//遍历所有子目录
            System.out.println(file1.getPath());
        }
    }

    private static List<File> filesList;
    private static List<File> directoryList;

    /**
     * @param file 目录
     *             返回目录下所有的文件和子目录
     */
    private static void getList(File file) {
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0)
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        directoryList.add(file1);
                        getList(file1);
                    } else {
                        filesList.add(file1);
                    }
                }
        } else {
            System.out.println("主目录不存在");
        }
    }
}

RandomAccessFile的使用

提供对文件内容的访问,既可以读文件,也可以写文件
支持随机访问文件,可以访问文件的任意位置
(1)java文件模型
在硬盘上的文件是byte byte....存储的,是数据的集合
(2)打开文件
两种模式:"rw"(读写),"r"(只读)
- RandomAccessFile raf=new RandomAccessFile(file,"rw")

  • 文件指针,打开文件时指针在开头pointer=0;

(3)写方法
raf.write(int)--->只写一个字节(后8位),同时指针指向下一个位置,准备再次写入
(4)读方法
int b=raf.read()---->读一个字节
(5)文件读写完毕后必须关闭

import java.io.*;
import java.util.Arrays;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:RandomAccessFile类读写
 */
public class Test {
    public static void main(String[] args) {
        File test = new File("D:\\log4j\\test");
        if (!test.exists()) {
            System.out.println(test.mkdir() ? "创建成功" : "创建失败");
        }
        File file = new File(test, "raf.bat");
        if (!file.exists()) {
            try {
                if (file.createNewFile()) {
                    //写文件
                    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
                    System.out.println("-----------------------------------");
                    System.out.println(randomAccessFile.getFilePointer());
                    randomAccessFile.write('A');
                    System.out.println("-----------------------------------");
                    System.out.println(randomAccessFile.getFilePointer());
                    randomAccessFile.write('B');
                    System.out.println("-----------------------------------");
                    System.out.println(randomAccessFile.getFilePointer());
//            int i = 0x7fffffff;
//            randomAccessFile.write(i >>> 24);
//            randomAccessFile.write(i >>> 16);
//            randomAccessFile.write(i >>> 8);
//            randomAccessFile.write(i);
//            System.out.println("-----------------------------------");
//            System.out.println(randomAccessFile.getFilePointer());
//            randomAccessFile.writeInt(i);
//            System.out.println("-----------------------------------");
//            System.out.println(randomAccessFile.getFilePointer());
                    String string = "猿";
                    byte[] bytes = string.getBytes("utf-8");
                    randomAccessFile.write(bytes);
                    System.out.println("-----------------------------------");
                    System.out.println(randomAccessFile.length());
                    //读文件,必须把指针放置头部
                    randomAccessFile.seek(0);
                    byte[] bytes1 = new byte[(int) randomAccessFile.length()];
                    randomAccessFile.read(bytes1);
                    System.out.println(Arrays.toString(bytes1));
                    System.out.println(new String(bytes1, "utf-8"));
                    randomAccessFile.close();
                } else {
                    System.out.println(file.getParentFile() + "目录下" + file.getName() + "文件,创建失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(file.delete() ? file.getName() + "删除成功" : file.getName() + "删除失败");
        }

    }
}

字节流的使用

  • 输入流InputStream
  • 输出流OutputStream

输入流

IO流,字符流
1.字节流
1)InputStream,OutputStream
InputStream抽象了应用程序读取数据的方式
OutputStream抽象了应用程序写出数据的方式
2)EOF=End 读到-1就读到结尾
3)输入流基本方法
int b=in.read(); 读取一个字节无符号填充到int底八位.-1是EFO
in.read(bute[] buf)
in.read(bute[] buf,int start,int size)
4)输出流基本方法
out.write(int b); 写出一个byte到流,b的底八位
out.write(bute[] buf) 将buf数组都写入到流
out.write(bute[] buf,int start,int size) 字节数组buf从start位置开始写size长度的字节流
5)FileInputStream--->具体实现了在文件上读取数据

test.txt文件内容:
test
sasd
ssd
dw
assd

asaswqwwdwd


test.txt
import java.io.*;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:InputStream类的使用
 */
public class Test {
    public static void main(String[] args) {
        File test = new File("D:\\log4j\\test.txt");
        try {
            printHex(test.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printHex(String fleName) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(fleName);
        int b;
        int i = 1;
        StringBuilder stringBuilder = new StringBuilder();
        while ((b = fileInputStream.read()) != -1) {
            if (b < 0xf) {
                stringBuilder.append("0");
            }
            stringBuilder.append(Integer.toHexString((b))).append(" ");
            if (i++ % 10 == 0) {
                stringBuilder.append("\n");
            }
        }
        fileInputStream.close();
        System.out.println(stringBuilder.toString());
    }
}
输出结果
import java.io.*;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:InputStream类的使用
 */
public class Test {
    public static void main(String[] args) {
        File test = new File("D:\\log4j\\test.txt");
        try {
            printHex2(test.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 一次性读取
     * byte类型8位,int类型32位
     * 0xff用于高24位清0
     *
     * @param fleName fleName
     * @throws IOException IOException
     */
    private static void printHex2(String fleName) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(fleName);
        byte[] buf = new byte[8 * 1024];
        int b;
        int j = 1;
        StringBuilder stringBuilder = new StringBuilder();
        while ((b = fileInputStream.read(buf, 0, buf.length)) != -1) {
            for (int i = 0; i < b; i++) {
                stringBuilder.append(Integer.toHexString((buf[i] & 0xff))).append(" ");
                if (j++ % 10 == 0) {
                    stringBuilder.append("\n");
                }
            }
        }
        fileInputStream.close();
        System.out.println(stringBuilder.toString());
    }
}
输出结果

输出流

6)FileOutputStream实现了向文件中写出byte数据的方法

import java.io.*;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:FileOutputStream类的使用
 */
public class Test {
    public static void main(String[] args) {
        File test = new File("D:\\log4j\\test.txt");
        try {
            writeHex(test.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeHex(String fleName) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(fleName);
        fileOutputStream.write('A');
        fileOutputStream.write('B');
        int a = 10;
        fileOutputStream.write(a >>> 24);
        fileOutputStream.write(a >>> 16);
        fileOutputStream.write(a >>> 8);
        fileOutputStream.write(a);
        byte[] bytes = "中国".getBytes("gbk");
        fileOutputStream.write(bytes);
        fileOutputStream.close();
        printHex(fleName);
    }

    private static void printHex(String fleName) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(fleName);
        int b;
        int i = 1;
        StringBuilder stringBuilder = new StringBuilder();
        while ((b = fileInputStream.read()) != -1) {
            if (b < 0xf) {
                stringBuilder.append("0");
            }
            stringBuilder.append(Integer.toHexString((b))).append(" ");
            if (i++ % 10 == 0) {
                stringBuilder.append("\n");
            }
        }
        fileInputStream.close();
        System.out.println(stringBuilder.toString());
    }
}

功能扩展

7)DataOutputStream和DataInputStream
对"流"功能的扩展,可以更加方便读取int,long,字符等类型数据
DataOutputStream
writeInt()/writeDouble()/writeUTF()

import java.io.*;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:DataOutputStream类
 */
public class Test {
    public static void main(String[] args) {
        File test = new File("D:\\log4j\\test.txt");
        try {
            writeHex(test.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeHex(String fleName) throws IOException {
        DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(fleName));
        dataOutputStream.writeInt(10);
        dataOutputStream.writeInt(-10);
        dataOutputStream.writeLong(10l);
        dataOutputStream.writeDouble(10.5d);
        dataOutputStream.writeUTF("中国");
        dataOutputStream.writeChars("中国");
        dataOutputStream.close();
        printHex(fleName);
    }

    private static void printHex(String fleName) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(fleName);
        int b;
        int i = 1;
        StringBuilder stringBuilder = new StringBuilder();
        while ((b = fileInputStream.read()) != -1) {
            if (b < 0xf) {
                stringBuilder.append("0");
            }
            stringBuilder.append(Integer.toHexString((b))).append(" ");
            if (i++ % 10 == 0) {
                stringBuilder.append("\n");
            }
        }
        fileInputStream.close();
        System.out.println(stringBuilder.toString());
    }
}
输出结果
import java.io.*;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:DataInputStream类
 */
public class Test {
    public static void main(String[] args) {
        File test = new File("D:\\log4j\\test.txt");
        try {
            writeHex(test.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeHex(String fleName) throws IOException {
        DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(fleName));
        dataOutputStream.writeInt(10);
        dataOutputStream.writeInt(-10);
        dataOutputStream.writeLong(10L);
        dataOutputStream.writeDouble(10.5D);
        dataOutputStream.writeUTF("中国");
        dataOutputStream.writeChars("中国");
        dataOutputStream.close();
        printHex(fleName);
        printHex2(fleName);
    }

    private static void printHex(String fleName) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(fleName);
        int b;
        int i = 1;
        StringBuilder stringBuilder = new StringBuilder();
        while ((b = fileInputStream.read()) != -1) {
            if (b < 0xf) {
                stringBuilder.append("0");
            }
            stringBuilder.append(Integer.toHexString((b))).append(" ");
            if (i++ % 10 == 0) {
                stringBuilder.append("\n");
            }
        }
        fileInputStream.close();
        System.out.println("printHex:\n" + stringBuilder.toString());
    }

    private static void printHex2(String fleName) throws IOException {
        DataInputStream dataInputStream = new DataInputStream(new FileInputStream(fleName));
        StringBuilder stringBuilder = new StringBuilder();
        int i = dataInputStream.readInt();
        stringBuilder.append(i).append("\n");
        i = dataInputStream.readInt();
        long l = dataInputStream.readLong();
        double d = dataInputStream.readDouble();
        String s = dataInputStream.readUTF();
        stringBuilder.append(i).append("\n");
        stringBuilder.append(l).append("\n");
        stringBuilder.append(d).append("\n");
        stringBuilder.append(s).append("\n");
        dataInputStream.close();
        System.out.println("printHex2:\n" + stringBuilder.toString());
    }
}
输出结果

字符流的使用

8)BufferedInputStream&BufferedOutputStream
这两个流类为IO提供了带缓冲区的操作,一般打开文件进行写入或读取操作时,都会加上缓冲,这种流模式提高了IO性能

import java.io.*;

/**
 * 创建人:二次猿
 * 创建日期:2018/8/31
 * 创建时间:10:17
 * 创建作用:BufferedInputStream&BufferedOutputStream
 */
public class Test {
    public static void main(String[] args) {
        File file = new File("D:\\log4j\\test.f4v");
        File toFile = new File("D:\\log4j\\test2.f4v");
        try {
            copy(file, toFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param file   file
     * @param toFile toFile
     * @throws IOException IOException
     */
    private static void copy(File file, File toFile) throws IOException {
        if (!file.exists()) {
            throw new IllegalArgumentException("文件" + file.getPath() + "不存在");
        } else {
            if (!file.isFile()) {
                throw new IllegalArgumentException(file.getPath() + "不是文件");
            } else {
                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(toFile));
                int c;
                while ((c = bufferedInputStream.read()) != -1) {
                    bufferedOutputStream.write(c);
                    bufferedOutputStream.flush();
                }
                bufferedInputStream.close();
                bufferedOutputStream.close();
            }
        }
    }


}

对象的序列化和反序列化

相关文章

  • 文件的编码,文件传输基础-Java IO流

    Java IO流 编码问题 gbk编码,英文占1个字节,中文占2个字节utf-8编码,英文占1个字节,中文占3个字...

  • 文件传输基础-Java IO流

    文件的编码 java.io.File类用于表示文件(目录)File类只用于表示文件(目录)的信息(名称、大小等),...

  • 文件传输基础——Java IO流

    了解 文件的编码 File类的使用 RandomAccessFile类的使用 字节流 字符流 对象的序列化和反序列...

  • 四、文件传输基础——Java IO流

    1、文件的编码(Java是双字符编码UTF-16be编码) GBK编码中文占2个字节,英文占1个字节。 UTF-8...

  • Java—IO

    Java—IO流 1.IO—File常用API及文件编码 separator:名称分隔符,用来拼接文件路径path...

  • java中读取文件和存储文件

    1、统一编码,java工程的编码统一用utf-8;2、 利用IO文件流的 InputStreamReader()和...

  • Java基础之IO流

    ##Java基础之IO流IO流常用几个类的关系如下: 字节流 字节输入流FileInputStream 读取文件用...

  • Java IO详解

    1 Java IO流的概念,分类 1.1 Java IO流的概念 java的IO是实现输入和输出的基础,可以方便的...

  • java IO入门笔记

    1.java IO流的概念,分类,类图 1.1. java IO 流的概念 java的io是实现输入和输出的基础,...

  • java流,文件,IO基础操作

    1.从控制台读入字符,字符串 2.读文件,写文件从file.txt文件中读取数据,然后存放到dest.txt文件中...

网友评论

      本文标题:文件的编码,文件传输基础-Java IO流

      本文链接:https://www.haomeiwen.com/subject/sgfxzftx.html