2015-08-09 58 views
0

我有一个传感器,将他收集的数据写入一个txt文件(连续,每秒一次),我唯一关心的数据是传感器收集的最后一个数据,我想要的是 用Matlab(或Java)分析数据,如何完成? 在此先感谢!同时读写matlab

回答

0

这只是的http://www.mathworks.com/help/matlab/ref/fgetl.html

fid = fopen('sensor.txt'); 
tline = fgetl(fid); 
while 1 
    if ischar(tline) 
     disp(tline) 
    else 
     pause(1) 
    end 
    tline = fgetl(fid); 
end 

这不是一个成品的解决方案稍作修改,想想当关闭文件。缺少flose(fid),代码当前以无限循环运行。使用CTRL + C退出它。

2

您需要能够观察文件以获取更新,然后在检测到更改时采取一些措施。我相信这之前必须与轮询机制完成的,但在Java 7,您可以使用一个WatchService

public static void main(String[] args) throws InterruptedException { 

    Path dir = Paths.get("src/main/resources/"); 
    try { 
     WatchService watcher = FileSystems.getDefault().newWatchService(); 
     WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); 

     while (true){ 
      watcher.take(); 
      List<WatchEvent<?>> events = key.pollEvents(); 
      // Handle update 

      key.reset(); 
     } 
    } catch (IOException x) { 
     System.err.println(x); 
    } 
} 

我建议你仔细想一下线程安全的,你如何处理更新 - 我建议在读取文件之前将文件复制到安全的“分段”位置,以避免与更新过程发生读/写冲突。