1、从文件中读取三行数据
1 String[] lines = new String[3]; 2 boolean readPointerFileSuccess = true; 3 4 try (Scanner scanner = new Scanner(pointerFile)) { 5 for (int i = 0; i < lines.length; i++) { 6 if (scanner.hasNextLine()) { 7 lines[i] = scanner.nextLine(); 8 } else { 9 readPointerFileSuccess = false; 10 } 11 } 12 }
2、写入文件
1 try(PrintWriter writer = new PrintWriter(pointerFile)){ 2 writer.println(logFileName); 3 writer.println(pointer); 4 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 5 String time = sdf.format(readDate); 6 writer.println(time); 7 writer.flush();//立即写入 8 }
3、RandomAccessFile读取数据
1 RandomAccessFile randAccessFile = new RandomAccessFile(fileName, "r"); 2 // 定位到文件的 pointer 3 randAccessFile.seek(pointer); 4 5 String line = readLine(randAccessFile, "GBK"); 6 7 8 public String readLine(RandomAccessFile randAccessFile, String charset) throws IOException { 9 10 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 11 12 int c = -1; 13 boolean eol = false; 14 15 while (!eol) { 16 switch (c = randAccessFile.read()) { 17 case -1: 18 case ' ': 19 eol = true; 20 break; 21 case ' ': 22 eol = true; 23 long cur = randAccessFile.getFilePointer(); 24 if ((randAccessFile.read()) != ' ') { 25 randAccessFile.seek(cur); 26 } 27 break; 28 default: 29 baos.write(c); 30 break; 31 } 32 } 33 34 if ((c == -1) && (baos.size() == 0)) { 35 return null; 36 } 37 38 return new String(baos.toByteArray(), charset); 39 }
4、RandomAccessFile读取数据
1 File file = new File(info.getName()); 2 3 RandomAccessFile raf = null; 4 try { 5 raf = new RandomAccessFile(file, "rw"); 6 } catch (FileNotFoundException e) { 7 e.printStackTrace(); 8 } 9 10 FileChannel cha = raf.getChannel(); 11 12 ByteBuffer buf = ByteBuffer.allocate(1024); 13 14 int size = 0; 15 16 StringBuffer sb = new StringBuffer(); 17 18 try { 19 while ((size = cha.read(buf)) != -1) { 20 21 buf.flip(); 22 23 byte[] buff = new byte[size]; 24 25 buf.get(buff); 26 27 sb.append(new String(buff, 0, size)); 28 29 } 30 } catch (IOException e) { 31 e.printStackTrace(); 32 } 33 34 String[] s = sb.toString().split("\}\,\{");