0%

java关于文件操作的总结

文件的编码

文本文件就是字符(字节)序列,是原始字符串按照某种编码方式编码而成的字节序列.常见编码有

  • 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");
//byte[] bytes=s.getBytes("utf-8");
for(byte b:bytes){//int 4 byte
System.out..println(Integer.toHexString(b & 0xff) + " ");
}

String str=new String(bytes,"utf-8");
System.out..println(str);//输出乱码,因为bytes是按gbk编码的
//String str=new String(bytes,"gbk");

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");
//System.out.println(file.exists());
if(!file.exists())
file.mkdir(); //file.mkdirs()多级目录
else
file.delete();
//是否是一个目录 如果是目录返回true,如果不是目录or目录不存在返回的是false
System.out.println(file.isDirectory());
//是否是一个文件
System.out.println(file.isFile());

//File file2 = new File("e:\\javaio\\日记1.txt");
File file2 = new File("e:\\javaio","日记1.txt");
if(!file2.exists())
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
file2.delete();
//常用的File对象的API
System.out.println(file);//file.toString()的内容
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());
}
}