Java IO – 在写入其他应用程序时读取一个大文件

前端之家收集整理的这篇文章主要介绍了Java IO – 在写入其他应用程序时读取一个大文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想使用java来读取weblogic日志文件,而weblogic正在将日志写入其中(缓冲),但我只想读取内容,当我开始阅读它时.

我怎样才能做到这一点 ?

  1. public class DemoReader implements Runnable{
  2. public void run() {
  3. File f = new File ("c:\\test.txt");
  4. long length = f.length();
  5. long readedBytes = 0;
  6. System.out.println(length);
  7. try {
  8. BufferedReader fr = new BufferedReader(new FileReader(f));
  9. String line = "";
  10. while((line = fr.readLine()) != null && readedBytes < length){
  11. readedBytes += line.getBytes().length;
  12. if(readedBytes > length){
  13. break;
  14. }else{
  15. System.out.println(line);
  16. }
  17. }
  18. } catch (FileNotFoundException e) {
  19. e.printStackTrace();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }
最佳答案
只要日志文件仅被锁定以进行写访问,您应该能够像@ karim79建议的那样将其复制.之后,副本属于您,因此您可以随心所欲地做任何事情.

下面是一些应该实现您所需要的代码 – 它只是将文件逐字节复制到System.out流:

  1. public class Main {
  2. public static void main(String[] args) throws IOException {
  3. // Identify your log file
  4. File file = new File("path/to/your/logs/example.log");
  5. // Work out the length at the start (before Weblogic starts writing again)
  6. long size = file.length();
  7. // Read in the data using a buffer
  8. InputStream is = new FileInputStream(file);
  9. BufferedInputStream bis = new BufferedInputStream(is);
  10. long byteCount=0;
  11. int result;
  12. do {
  13. // Read a single byte
  14. result = bis.read();
  15. if (result != -1)
  16. {
  17. // Do something with your log
  18. System.out.write(result);
  19. } else {
  20. // Reached EOF
  21. break;
  22. }
  23. byteCount++;
  24. } while (byteCount

你去吧

有关日志文件的说明

如果日志文件很大(例如> 1Gb),那么您应该考虑更改日志配置以合并滚动日志文件,该日志文件自动将日志分解为块(例如1Mb),这些块更适合在shell编辑器中查看(像vim).

猜你在找的Java相关文章