2011-12-26 46 views
0

我想读取文本文件,然后获得文件读取的偏移量。我尝试了下面的程序,但事情是我不想使用RandomAccessFile,我该怎么做。读取文件,然后跳转到结尾

RandomAccessFile access = null; 
       try { 
        access = new RandomAccessFile(file, "r"); 

        if (file.length() < addFileLen) { 
         access.seek(file.length()); 
        } else { 
         access.seek(addFileLen); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       String line = null; 
       try { 

        while ((line = access.readLine()) != null) { 

         System.out.println(line); 
         addFileLen = file.length(); 

        } 
+0

如果你不想使用RandomAccessFile,你更喜欢什么? – JRideout 2011-12-26 12:53:07

+0

任何可以工作的东西。 – Rookie 2011-12-26 12:53:32

+1

http://docs.oracle.com/javase/tutorial/essential/io/file.html 查找关于ByteChannels的信息 – Kris 2011-12-26 12:54:21

回答

1

如果要连续读取文件,可以执行以下操作。这通过不实际阅读文件的结尾来工作。您遇到的问题是,您可能在最后没有完整的行或者甚至没有完整的多字节字符。

class FileUpdater { 
    private static final long MAX_SIZE = 64 * 1024; 
    private static final byte[] NO_BYTES = {}; 

    private final FileInputStream in; 
    private long readSoFar = 0; 

    public FileUpdater(File file) throws FileNotFoundException { 
     this.in = new FileInputStream(file); 
    } 

    public byte[] read() throws IOException { 
     long size = in.getChannel().size(); 
     long toRead = size - readSoFar; 
     if (toRead > MAX_SIZE) 
      toRead = MAX_SIZE; 
     if (toRead == 0) 
      return NO_BYTES; 
     byte[] bytes = new byte[(int) toRead]; 
     in.read(bytes); 
     readSoFar += toRead; 
     return bytes; 
    }  
} 
+0

我想获得数据线,因为我想解析整个日志行并根据指定的严重程度将其发送给邮件。您认为这样做会有额外的开销。 – Rookie 2011-12-27 06:30:35

+0

该文件不保证有整行,所以你不能假设有整行。相反,您需要自己扫描数据并保存字节,而不必在下一次读取时添加新行。虽然开销很小,但与使用BufferedReader相同,与读取IO的成本相比非常小。 – 2011-12-27 09:57:46

相关问题