1.编码
gbk编码:中文占2个字节,英文占1个字节
utf-8编码:中文占3个字节,英文占1个字节
utf-16be编码:中文占2个字节,英文占2个字节
2.File类
File类只用于表示文件(目录)的信息(大小、名称等),不能用于文件内容的访问
3种分隔符写法:
File file = new File("D:" + File.separator + "test");
File file = new File("D:\\test");
File file = new File("D:/test");
file.mkdir();//创建目录(不能创建多级目录)
file.mkdirs();//创建多级目录
file.createNewFile();//创建文件
遍历目录文件
public class FileUtils {
public static void listDirectory(File dir)throws IOException{
if(!dir.exists()){
throw new IllegalArgumentException("目录:"+dir+"不存在!");
}
if(!dir.isDirectory()){
throw new IllegalArgumentException(dir+"不是目录!");
}
/*String[] files = dir.list();
for (String file : files) {
System.out.println(file);
}*/
File[] files = dir.listFiles();
for (File file : files) {
if(file.isDirectory()){
listDirectory(file);
}else{
System.out.println(file);
}
}
}
}
RandomAccessFile java提供的对文件内容的访问,既可以读文件,也可以写文件
RandomAccessFile支持随机访问文件
FileInputStream
public class IOUtil {
/**
* 单字节读取不适合大文件,效率很低
* @param fileName
* @throws IOException
*/
public static void printHex(String fileName) throws IOException {
InputStream in = new FileInputStream(fileName);
int b;
int i = 1;
while ((b = in.read()) != -1) {
if (b <= 0xf) {
System.out.print("0");
}
System.out.print(Integer.toHexString(b) + " ");
if (i++ % 10 == 0)
System.out.println();
}
in.close();
}
/**
* 批量读取,对大文件而言效率高
* @param fileName
* @throws IOException
*/
public static void printHexByByte(String fileName) throws IOException {
InputStream in = new FileInputStream(fileName);
byte[] buf = new byte[1024];
int count = 1;
int bytes;
while ((bytes = in.read(buf, 0, buf.length)) != -1) {
for (int i = 0; i < bytes; i++) {
if (buf[i] <= 0xf) {
System.out.print("0");
}
System.out.print(Integer.toHexString(buf[i] & 0xff) + " ");
if (count++ % 10 == 0)
System.out.println();
}
}
in.close();
}
}