编码:
GBK:中文字符占位2字节,英文1字节;
UTF-8:中文字符占位3字节,英文1字节;
// 将字符串转换为字节,再将字节转换为16进制的int输出
String s = "你好";
byte[] b = s.getBytes();
for(byte b1 : b){
System.out.print(Integer.toHexString( b1 & 0xff) + ",");//0xff只显示后两位
}
文本文件就是字节序列,不同编码访问会乱码;
java.io.File类 (只能用于表示文件(目录)的信息,不能访问内容)
File file = new File(D:\\file.txt); //新建文件
常见方法:file.exists()文件是否存在;isDirectory()是否为目录;mkdir()创建目录;isFile()是否为文件;createNewFile()创建文件;delete()删除;
list()遍历文件,返回的是String类型;listFiles()遍历文件,返回的是File类型;
遍历目录下所有的文件:
public static void listDirectory(File dir) throws IOException{
if(!dir.exists()){
throw new IllegalAccessException("目录" + dir + "不存在");
}
File[] files = dir.listFiles();
if(files != null && files.size() > 0){
for(File file : files){
if(file.isDirectory()){
listDirectory(file); //递归
}else{
System.out.print(file + ",");
}
}
}
}
RandomAccessFile类
支持随机访问文件,可以读写文件中任意位置的内容,类似迅雷的分批下载后整合;
在硬盘上的文件都是byte byte byte存储的,是数据的集合;
RandomAccessFile raf = new RandomAccessFile(file , "rw");//可读写
打开文件时pointer指针在开头,即pointer = 0;
写操作:raf.write();还有很多 writeUTF()等;
写完后指针是指向最后一个的,所以当你写完后想要读取的话需要将指针归位,raf.seek(0);,之后就能raf.read();
一次性读取,把文件中的内容都读到字节数组中(这需要耗费大量的内存,因为创建数组时宽度越大,耗费的内存越多)
byte[] buf = new byte[(int)raf.length()];
raf.read(buf);
//读取内容,通过String的构造参数输出
String s = new String(buf,0,raf.length(),"gbk");
字节流(InputStream、OutputStream)
InputStream抽象了应用程序读取数据的方式,EOF = END OF File 读到-1时表示文件以读取完毕
FileInputStream in = new FileInputStream(fileName);
in.read()逐字节读取;如果读不到值则为-1,代表着已经读取到结尾了;
in.read(byte[] buf);将数据读取到字节数组中;
in.read(buf,int start,int size);从start位置开始存放长度为size长度的数据到buf数组中;
byte[] buf = new byte[1 * 1024]; //1 * 1024表示1024字节,代表512个汉字gbk编码;
int bytes = in.read(buf,0,buf.length());//返回的是读取到的字节数;
for(int i = 0; i < bytes ; i++){
System.out.print(Integer.toHexString(buf[i] & 0xff) + ",");
}
FileOutputStream out = new FileOutputStream("xxx",true);
true代表文件存在则在其内容中追加,不写则无论有无文件,都创建;
复制粘贴文件实现代码:
public static void Copy(String needCopy, String Copyto){
FileInputStream in = new FileInputStream(needCopy);
FileOutputStream out = new FileOutputStream(Copyto);
type[] buf = new type[2 * 1024]; //创建一个字节数组用于存放读取文件的字节
int a; //用于表示读取到的字节数,等于-1则表示文件已经读取完毕
while( a = in.read(buf,0,buf.length()) != -1){
out.write(buf); //将数组中的字节写出到文件中
out.flush(); //一般buffer缓冲才写这个,将缓冲中的数据写出去,相当于清空
}
in.close(); //关闭流
out.close();
}
DataInputStream是对流功能的扩展,可以更加方便的读取int,Long,字符等数据类型。
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readInt();等方法,一次可读写多字节;