編碼淺析
編碼格式實例
文本文件就是字符序列,它可以是任意編碼,中文機器上創建文本文件時,默認ansi編碼。
不同的編碼格式下輸出存在差異:
將同一個字符串以不同編碼格式讀取,然后輸出。
String string1 = "測試12AB";
byte[] bytes = new byte[0];
byte[] bytes2 = new byte[0];
byte[] bytes3 = new byte[0];
try {
bytes = string1.getBytes("utf-8");
bytes2 = string1.getBytes("gbk");
bytes3 = string1.getBytes("utf-16be");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(new String(bytes));
System.out.println(new String(bytes2));
System.out.println(new String(bytes3));
輸出結果.png
指定相對應編碼格式后,可以正常顯示。
System.out.println(new String(bytes3,"utf-16be"));
File類
File只能代表文件(路徑),用于表示文件的信息等,不能用于顯示文件內容。
常用方法:
File file = new File("./aimFile");
if (file.exists()){
file.delete();//delete file
}else {
file.mkdir();//make directory
}
File file2 = new File("./","file.txt");
try {
file2.createNewFile();//create file
} catch (IOException e) {
e.printStackTrace();
}
//getFileName
System.out.println("getFileName (File is directory):" + file.getName()); //aimFile
System.out.println("getFileName (File is file):" + file2.getName()); //file.txt
RandomAccessFile
與File對象不同,RandomAccessFile可以用于讀寫文件,可以讀寫于文件的任意位置。
創建該類型的時候除了file對象,還需要讀寫方式:r rw
RandomAccessFile randomAccessFile = new RandomAccessFile(new File("F:\\HS"),"rw");
randomAccessFile.seek(0);
byte[] bytes = new byte[(int)randomAccessFile.length()];
randomAccessFile.read(bytes);
因為是隨機讀寫,所以該對象內部含有一個pointer,初始pointer為0;
可以使用seek定位pointer,從而將其內容讀入byte[]。