使用随机流(RandomAccessFile)读取文件中的汉字
读取一行的方法:
String filePath="F:\\code\\java\\text\\demo\\db\\"; File file = new File(filePath); RandomAccessFile randomAccessFile=new RandomAccessFile(file,"r"); String string=new String(().getBytes("ISO-8859-1"), "gbk") ();
读取全部的方法:
String filePath="F:\\code\\java\\text\\demo\\db\\"; File file = new File(filePath); RandomAccessFile randomAccessFile=new RandomAccessFile(file, "r"); byte bytes[]=new byte[999]; (bytes); ( new String(bytes,"gbk")); ();
使用随机流(RandomAccessFile)读取文件最后一行数据
public static void main(String[] args) throws IOException { String filePath="F:\\code\\java\\text\\demo\\db\\"; (getFileEndLine(filePath)); } /** * 获取文件最后一行数据,文件中没有数据就返回"" * @param filePath 文件路径 * @return 文件最后一行数据,文件中没有数据就返回"" * @throws IOException */ public static String getFileEndLine(String filePath) throws IOException { File file = new File(filePath); RandomAccessFile randomAccessFile=new RandomAccessFile(file, "r"); //获得文件中数据的长度 long pos=(); //判断文件是否为空 if(pos==0){ return ""; } String endLine=getEndLine(randomAccessFile,pos) (); return endLine; } /** * 循环获取文件最后一行数据 */ private static String getEndLine(RandomAccessFile randomAccessFile,long pos) throws IOException { String endLine=""; while (pos>0){ //使光标向前移动一位 pos--; //是读取文件数据的光标移动到pos位置 (pos); //下面两个if的顺序不能颠倒 //预防文件只有第一行有不为空的数据 和 文件中只有空格、换行的情况出现 if (pos==0){ //读取一行数据,从光标位置到改行尾部的数据 endLine = (); //()检查字符串是否为空 //endLine=" \t \n"也判定为空 if ((endLine)) { endLine=""; } } if(()=='\n') { //读取一行数据,从光标位置到改行尾部的数据 endLine = (); //()检查字符串是否为空 //endLine=" \t \n"也判定为空 if ((endLine)) { endLine = ""; } else { break; } } } return endLine; }