JAVA写文件


Java写字符文件和写二进制文件有些不同,具体代码如下:

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class OutBinary {
    public static main (String[] args) {
        String url = "X:\\yourUrl\\";
        String fileName = "character.txt";
        String binFileName = "binary.dat";
        
        // 写字符文件
        File f = new File(url + fileName);
        FileOutputStream fop = new FileOutputStream(f);
        OutputStreamWriter writer = new OutputStream(fop);
        writer.append("content...");
        writer.close();
        fop.close();
        
        // 写二进制文件
        f = new File(url + binFileName);
        fop = new FileOutputStream(f);
        String hexStr = "8311050108001102";
        byte[] bytes = hexStringToByte(hexStr);
        fop.write(bytes);
        fop.close();
    }
    
    // 将十六进制字符串转换为byte数组
    private static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] cs = hex.toCharArray();
        
        for (int i = 0; i < len; i+=2) {
            result[i] = (byte) ((toByte(cs[i]) << 4) | (toByte(cs[i+1])));
        }
        
        return result;
    }
    
    private static byte toByte(char c) {
        byte b = (byte) ("0123456789ABCDEF".indexOf(c));
        return b;
    }
}