亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 屬性類錯誤

Java 屬性類錯誤

臨摹微笑 2022-12-28 14:12:08
我有這段代碼。// On a threadtry {    WatchService watcher = FileSystems.getDefault().newWatchService();    Path directory = Paths.get("properties");    WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);    while (true) {        for (WatchEvent<?> event : watchKey.pollEvents()) {            Path changed = (Path) event.context();            if (changed.toString().equals("radar.properties")) {                System.out.println("read call:");                readProperties();            }        }        if (!watchKey.reset()) {            break;        }    }} catch (IOException e) {    FCSLogger.LOGGER.log(Level.SEVERE, "Exception while setting up WatchService", e);}// Method called by the above codeprivate void readProperties() {    try {        InputStream input = new FileInputStream(Paths.get("properties", "radar.properties").toString());        Properties prop = new Properties();        prop.load(input);        updateRate = Integer.parseInt(prop.getProperty("updateRate"));        System.out.println(updateRate);        input.close();    } catch (IOException e) {        e.printStackTrace();    }}它在第一次調用時返回正確的結果,然后阻塞整個線程。我已經隔離了這個方法中的錯誤,因為當沒有調用這個方法時,其他一切都完美無缺。我想知道我在這里做錯了什么。控制臺輸出快照:// First change of file:read call:10read call:10// Second change of file:read call:// I keep changing but nothing happens:
查看完整描述

1 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

它可能是readPropertiesthrows NumberFormatException,并導致您的觀察線程退出。


您可以包裝調用readProperties并捕獲異常;這樣至少觀察者會在出現異常情況時繼續觀察。


你應該使用take, 以便觀察線程阻塞。您當前的解決方案導致 100% 的 CPU 使用率。


請參閱下面修改后的代碼。我添加了一個編寫器線程來更新文件,并且(不出所料?)readProperties可能會失敗,因為我們在寫入文件時正在訪問該文件。一個可能的輸出是:


....

property=5000

property=null

java.lang.NumberFormatException: null

  at java.base/java.lang.Integer.parseInt(Integer.java:614)

  at java.base/java.lang.Integer.parseInt(Integer.java:770)

  at cl.ClientPoll.readProperties(ClientPoll.java:26)

  at cl.ClientPoll.run(ClientPoll.java:46)

property=6000

property=7000

....

因此在觀看時,您可以: 跳過錯誤并繼續;或使用其他API,使正在寫入的文件在寫入時被鎖定。


示例代碼


package cl;


import java.io.File;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.nio.file.FileSystems;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardWatchEventKinds;

import java.nio.file.WatchEvent;

import java.nio.file.WatchKey;

import java.nio.file.WatchService;

import java.util.Properties;


public class ClientPoll extends Thread {

  private void readProperties() {

    try {

      Path path = Paths.get("radar.properties");

      InputStream input =new FileInputStream(path.toString());

      Properties prop = new Properties();

      prop.load(input);

      String property = prop.getProperty("updateRate");

      System.out.println("property="+property);

      int updateRate = Integer.parseInt(property);

//      System.out.println(updateRate);

      input.close();

    } catch (IOException e) {

      e.printStackTrace(System.out);

    }

  }


  @Override

  public void run() {

    try {

      WatchService watcher = FileSystems.getDefault().newWatchService();

      Path directory = Paths.get(".");

      WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

      while (true) {

        WatchKey wk = watcher.take();

        for (WatchEvent<?> event : wk.pollEvents()) {

          Path changed = (Path) event.context();

          if (changed.toString().equals("radar.properties")) {

            try {

              readProperties();

            } catch (Exception e) {

              e.printStackTrace(System.out);

            }

          }

        }

        if (!watchKey.reset()) {

          break;

        }

      }

    } catch (IOException e) {

      e.printStackTrace(System.out);

    } catch (InterruptedException e) {

      e.printStackTrace();

    }

  }


  public static void main(String[] args) {

    new ClientPoll().start();

    new Writer().start();

  }

}


class Writer extends Thread {

  @Override

  public void run() {

    try {

      for (int i=0;i<10;i++) {

        File f = new File("radar.properties");

        FileWriter fw = new FileWriter(f);

        fw.write("updateRate="+i*1000);

        fw.close();

        sleep(1000L);

      }

    } catch (Exception e) {

      e.printStackTrace(System.out);

    }

    System.out.println("exit");

    System.exit(0);

  }

}



查看完整回答
反對 回復 2022-12-28
  • 1 回答
  • 0 關注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號