同时读写Matlab

时间:2015-08-09 10:14:28

标签: java matlab file

我有一个传感器将他收集的数据写入txt文件(连续,每秒一个),我关心的唯一数据是传感器收集的最后一个数据, 我想用Matlab(或Java)分析数据,怎么做? 提前谢谢!

2 个答案:

答案 0 :(得分: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);
    }
}

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

答案 1 :(得分: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 退出。

相关问题