文件的编码
文本文件就是字符(字节)序列,是原始字符串按照某种编码方式编码而成的字节序列.常见编码有
- utf-8 中文3字节 英文1字节
- ansi 扩展的ASCII编码 中文2字节 英文1字节
- GBK 中文系统下,ansi即GBK,是基于GB2312的扩展 中文2字节 英文1字节
- utf-16be java双字节编码 中文2字节 英文2字节
1 2 3 4 5 6 7 8 9 10
| String s="中文abc"; byte[] bytes=s.getBytes("gbk");
for(byte b:bytes){ System.out..println(Integer.toHexString(b & 0xff) + " "); }
String str=new String(bytes,"utf-8"); System.out..println(str);
|
File类
java.io.File类用于表示文件和目录,但不能访问文件的内容,用法示例:
1 2 3
| file.getAbsolutePath(); file.getName(); file.getParent();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public static void main(String[] args) { File file = new File("E:\\javaio\\imooc"); if(!file.exists()) file.mkdir(); else file.delete(); System.out.println(file.isDirectory()); System.out.println(file.isFile()); File file2 = new File("e:\\javaio","日记1.txt"); if(!file2.exists()) try { file2.createNewFile(); } catch (IOException e) { e.printStackTrace(); } else file2.delete(); System.out.println(file); System.out.println(file.getParentFile().getAbsolutePath()); }
|
RandomAccessFile类
提供对文件内容的访问,支持随机读写文件.文件读写完毕应关闭close()
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| ```writeInt()```写int 4个字节 ```read()```一次只读一个字节 ```getFilePointer()```获取文件指针 ```seek()```移动文件指针 ```java public class RandomAccessFileSeriaDemo { public static void main(String[] args)throws IOException { File demo = new File("demo1"); if (!demo.exists()) demo.mkdir(); File file = new File(demo, "raf.dat"); if (!file.exists()) file.createNewFile(); //打开文件,进行随机读写 RandomAccessFile raf = new RandomAccessFile(file, "rw"); /*序列化*/ //写int 4 byte int i = 0x7ffffff; raf.write(i >>> 24);//右移24位 写高8位 raf.write(i >>> 16); raf.write(i >>> 8); raf.write(i); // raf.writeInt(i); System.out.println(raf.getFilePointer()); } }
|