Read from a file continuously

Hello all.
I wonder if there is an easy way to read from a file so that the currect contents of the file are always available within a Java program.
For instance:
1. The file "text.txt" has one line: "hello"
2. Open the file from a Java program; it has the line "hello"
3. Somebody adds another line to the file: "bye"
4. The Java program is noticed about 3. so that the line "bye" can be read
Something like "tail -f" or a named pipe (fifo) in Unix.
Thanks in advance.
God bless,
Jaime

No, this is NOT a solution. Once FileReader has encountered an EOF condition once, it will never go back to the file descriptor to see if there might be some more available. (For that reason, also reader.ready() will never return true again, no matter how much is appended to the file.) I tried this on Java 1.5.0_11 on Solaris.
The other proposed solution, checking the file length periodically using the File length() method and then re-opening the file if the length is different, is also seriously flawed for several reasons:
(a) If the file is renamed, you have no way of telling whether the file you already opened is modified -- the next time you call file.length(), it would fail since the old name doesn't exist any more, or, even worse, if meanwhile a new file was created under the old name, you'd be looking at a different file, not the one you've opened for reading!
(b) If you do detect a change, having to reopen the file as a RandomAccessFile to be able to seek to the last read position is bad because you have to implement your own buffering (can't wrap BufferedReader around it, obviously), AND it suffers from the same file rename problem! The file you re-open might be a different one, so seeking to the last read position would land you at an arbitrary spot in a different file, and you wouldn't even know it!!!
As a conclusion, it is apparently not possible to implement something as elementary as "tail -f" in Java correctly!
Someone will have to think about that. Yes, I saw the argument that this may not be implementable on ALL kinds of file systems and hence not portable, but just because Windows file handling is broken, this shouldn't mean that Java file handling has to be broken on all decent platforms as well!
:-(

Similar Messages

  • UPDATE : Toshiba Recovery Wizard 'cannot read from source file or disk' error (satellite L500)

    UPDATE 2: Phoned Toshiba tech support again, guided by techie to begin the recovery again. Just before phoning I was able to go into recovery options and view the drive setup and all the files that couldn't be read are on the CD so I've no idea why the error kept occuring, and neither did the techie. Fingers crossed it works this time but I'm not overly hopefully given that we've just done exactly the same as I did before.  UPDATE 1: I got into the BIOS and reset everything back to defaults and yay, my toshiba recovery wizard now starts! :-D  On the down side, when trying to do a factory default software / out of the box recovery I continually get error messages with regards to copying the files, for example 
    cannot read from source file or disk
    7z.dll
    Type application extension
    size 585kb
    date modified 7/14/2009 10.26pm
    other read / copy errors include PREINST6.SWM, BOOT_32, BOOTPRIORITY, CHECKMAXPTSIZE, CHGBOOT, CPU, CPUCHECK, CREATEPARTITION, CTRLDRVINFO, DISKWIPE, DMI, DPINST32, EBLIB.DLL, ERRORDIALOG, EW3BOOTSEQ, FWLINK, FWLINK.SYS, GETHDDINFO, GETKEYSTATE, IMAGEX, INFILED, INITRECAREA, KRAIADAPI.DLL ..... at which point I decided to 'skip all' :-/
    Any explanations as to what's going on and how I might be able to fix it would be very much appreciated! :-)  Thank you!
    I have a two and half year old satellite L500 with an Intel i-3 and 4 gigs of RAM, on which I was running Windows 7.
    Admittedly it’s had rather a hard life (I ran some very demanding CAD / graphics software on it) but it had always performed well until just recently, when after suffering several BSOD (which had never happened before), the hard drive failed.
    I partitioned and formatted a brand new hard drive (which is perfectly fine and functions normally when hooked up to another laptop with a SATA to USB cable) and obtained system recovery discs from Toshiba.  Unfortunately, when I try and run the first disc, windows starts to load files but then generates an error screen with the message Error F3-F100-0003 and a request to turn the computer off.  
    When I use the windows Memory Diagnostic to get into the Windows Boot Manager Screen I get the following;
    Windows failed to start.  A recent hardware / software change might be the case.
    To fix the problem
    Insert your windows installation disc and restart your computer
    Choose your language settings and click ‘next’
    Click ‘repair your computer’
    File: \boot\memtest.exe
    Status: 0xc000000f
    Info: the selected entry could not be loaded because the application is missing or corrupt.
    I can also use F8 on startup to get into the advanced boot options but selecting any of them simply results in the F3-F100-0003 error message.  I’ve run a memory test using the UBCD, which tells me the memory is fine, and tried another hard drive (which also works perfectly well in another laptop) but no joy.  On phoning Toshiba support the techie said my hard drive had failed, but as I say, both hard drives are perfectly fine / usable when hooked up to another laptop.  I’m now completely stuck as to what the problem is and how I might resolve it – any advice / suggestions would be most gratefully received! Thank you in advance :-)

    Satellite L655-S5096
    Downloads here.
    the second disc gives me the the "cannot read from source file or disk PREINST8.SWM"
    My best guess is that the disc is not readable. Try copying it to another. Sometimes that works.
    Otherwise, order new discs from Toshiba.
    -Jerry

  • Read from spreedsheet file dont read the file correctly

    Hi, i have the problem that i want to show my voltage output (4 channels) on a graph, by saving the data (the saving process is in a SubVI) on the PC  and reloading it in the mainVI when all actions are done. If i open the file with a editor, like UltraEdit, the data looks right, but on the graph, some parts of the voltage output are shown wrong (as vertical instead of horizontal line)... Anyone got a idea why? or how to fix it?
    Thanks and greetings (and sorry for my bad english ) Mari0
    attached:
    -example voltage output (.lvm)
    -code extract (.vi)
    -picture with wrong parts (.jpg)
    Attachments:
    VoltageOutputReload.vi ‏22 KB
    SignalOutput.txt ‏4044 KB
    New Bitmap Image.jpg ‏1219 KB

    First, let's get the chastizing out of the way:
    Was it really necessary to upload a 4 MB text file as is? Ever hear of compression?
    DO NOT UPLOAD BITMAP FILES OR CHANGE THE EXTENSIONS TO GET AROUND THE BAN ON BITMAPS. THERE IS A REASON THE BAN IS THERE.
    I don't understand what your VI's purpose is. Why are you continuously reading the file in a loop? Is this something you created on the fly for demonstration? If so, the Read From Spreadsheet File needs a True wired to the transpose? input. The graph is showing you exactly what's in the data file. Look at your data. At line 66100 it jumps.
    NOTE HOW I DID NOT UPLOAD A BITMAP.

  • "Read from Binary File" and efficiency

    For the first time I have tried using Read from Binary File on sizable data files, and I'm seeing some real performance problems. To prevent possible data loss, I write data as I receive them from DAQ, 10 times per second. What I write is a 2-D array of double, 1000 data points x 2-4 channels. When reading in the file, I wish I could read it as a 3-D array, all at once. That doesn't seem supported, so I repeatedly do reads of 2-D array, and use a shift register with Build Array to assemble the 3-D array that I really need. But it's incredibly slow! It seems that I can only read a few hundred of these 2-D items per second.
    It also occurred to me that the Build Array being used in a shift register to keep adding on to the array, could be a quadratic-time operation depending on how it is implemented. Continually and repeatedly allocating bigger and bigger chunks of memory, and copying the growing array at every step.
    So I'm looking for suggestions on how to efficiently store, efficiently read, and efficiently reassemble my data into the 3-D array that I need. Perhaps I could simplify life if I had  "write raw data" and "read raw data" operations that write and read only the numbers and no metadata.then I could write the file and read it back in any size chunks I please -- and read it with other programs besides. But I don't see them in the menus.
    Suggestions?
    Ken
    Solved!
    Go to Solution.

    I quote the detailed help from Read from Binary File:
    data type sets the type of data the function uses to read from
    the binary file. The function interprets the data starting at the current file
    position to be count instances of data type.
    If the type is an array, string, or cluster containing an array or string, the
    function assumes that each instance of that data type contains size information.
    If an instance does not include size information, the function misinterprets the
    data. If LabVIEW determines that the data does not match the type, it sets data
    to the default for the specified type and returns an error.
    So I see how I could write data without any array metadata by turning off "prepend array or string size information", but I don't see any way to read it back in such bare form. If I did, I'd have to tell it how long an array to read, and I don't see where to do that. If I could overcome this, I could indeed read in much larger chunks.
    I'll try the auto-indexing tunnel anyway. I didn't tell you the whole truth, the 3-D array is actually further sliced up based on metadata that I carry, and ends up as a 4-D array of "runs". But I can do that after the fact instead of trying to do it with shift registers as I'm reading.
    Thanks,
    Ken

  • Using Scanner and FileReader to read from a file in real time

    Hi
    I would like to read continually from a text file (which is continually being appended to) and display each line as it appears in the textfile (in a text area).
    What I would like to know is do I have to continually reopen the file (using FileReader) and buffer it into a Scanner everytime I want to read the changes made to it? There must be a better way.
    Much appreciation for any help.

    Umm .. I hope you're doing that in a separate worker
    thread as otherwise you would block the EDT from
    processing events like paint (thus never showing you
    anything you append to the text area).Well that code fell under the run method of a class that is seperate to the main class, so it was called in a new thread. In desperation I've tried calling threads within threads (dangerous I know): remoteHandler's run method is called by a JButton's action listener...
    private class remoteFHandler implements Runnable {
         int lineNum;
         int  win, x, y, count, num = -999;
         remoteFHandler(){
              lineNum = 0;
         public synchronized void run() {
              while(showScreen == true){
                   readingRF = true;
                   innerHandler read = new innerHandler();
                   Thread t = new Thread(read);
                   t.start();                      
         //Wait 5 a seconds before checking if there is anymore text
                 try {
                         textArea.append("Waiting to reopen \n"); //DEBUG
                   t.join();
                   wait(5000);
                 } catch (InterruptedException e){
                   System.out.println("File reading interrupted");
                   return;
                }// while
              readingRF = false;
              return;
         } //run()
         private class innerHandler implements Runnable{
              innerHandler(){
              public synchronized void run(){
                   try {
                        outFile = new File("/data/wrmwind_08/testText.txt");
                        if (outFile!=null) textArea.append("File last modified: " + outFile.lastModified() + "\n"); //DEBUG
                        fs = new Scanner(new BufferedReader(new FileReader(outFile)));
                        if (fs!=null) textArea.append("File opened stream \n"); //DEBUG
                        fs.useDelimiter("\\r");
                      } catch(IOException e){
                        System.out.println("Problems opening file. IO exception: " + e.toString());
                        return;
                      if (fs!=null){
                        readAndDisplay();
                        fs.close();
                        fs = null;
                        if (fs==null) textArea.append("File closed \n"); //DEBUG
                   return;
         }//innerHandler
            private void readAndDisplay(){ //reads from a file and displays in a text field until there are no new lines  then returns
         }//readAndDisplay()
    }//remoteHandlerThe strange thing is that the when I modify the text file while the program is running, that time of last modification is detected and displayed in the text area yet I can't get to read the new line that's been added....

  • Cannot delete itunes from pc,message states. a network error occurred while attempting to read from the file C:\windows\installer\itunes.msi

    ITUNES WILL NOT DELETE FROM ADD @ REMOVE PROGRAMS,
    MESSAGE, READS  a network error occured while attempting to read from the file  C:WINDOWS\installer\iTunes.msi

    All sorted now just needed to repair itunes from control panel

  • Why does Read from Text file default to array of 9 elements

    I am writing to a text file starting with a type def. cluster (control) of say 15 dbl numeric elements, that works fine I open the tab-delimited text file and all of the elements appear in the file.  However when I read from the same text file back to the same type def. cluster (indicator), the read from text file defaults to 9 elements?? Is there a way to control how many elements are read from the file.  This all works great when I initially use a cluster of 9 elements and read back to a cluster of 9 elements.
    Solved!
    Go to Solution.

    From the LabVIEW Help: http://zone.ni.com/reference/en-XX/help/371361G-01/glang/array_to_cluster/
    Converts a 1D array to a cluster of elements of the same type as the array elements. Right-click the function and select Cluster Size from the shortcut menu to set the number of elements in the cluster.
    The default is nine. The maximum cluster size for this function is 256.
    Aside: so, how many times has this question been asked over the years?

  • How to open saved files using 'read from text file' function

    Hi everyone, I am having a hard time trying to solve the this particular problem ( probably because I am a newb to lanbview ). Anyway , I am able to save the acquired waveforms by using the 'Write to text file' icon. I did manually modify the block diagram of the 'Write to text file' icon and create the correct number of connector so as to make my program work. But now I have no idea on how to modify the block diagram of the 'Read from text file' block diagram to make my program 'open' my saved waveforms. Or i do not have to modify anything from the block diagram of the 'Read from text file'? Can anyone teach/help me connect up? Do i need the build array on the "open" page?
    Here are some screenshots on part of my program  
    let me know if you guys would need more information / screenshots thank you!
    Attachments:
    ss_save.jpg ‏94 KB
    ss_open.jpg ‏94 KB
    modified_writetotextfile.jpg ‏99 KB

    Ohmy, thanks altenbach. oh yeah i forgot about those sub VIs. will upload them now. Was rather demoralized after reading the comments and really struck me on how weak i'm at on labview really hope to get this done. But of course i have to study through and see how it works. Actually i am going to replace those 'signal generators sub vi' with ThoughtTechonology's sample code so i can obtain data waveforms real-time using Electrocardiography (ECG) ,Electromyography (EMG ) and Electroencephalography (EEG) hopefully i can find out how to connect the sample code.
    ( ps . cant connect it now unless my program is working otherwise labview will crash ) 
    ( p.s.s the encoder of my biofeedback trainer already acts as an DAQ so i wont need to place an DAQ assistant in my block diagram i suppose )
    The sample code of ThoughtTechnology is named as attachment.ashx.vi. too bad i cant use it and present it as my project
    Attachments:
    frequency detactor.vi ‏53 KB
    signal generator.vi ‏13 KB
    attachment.ashx.vi ‏40 KB

  • LabVIEW for ARM 2009 Read from text file bug

    Hello,
    If you use the read from text file vi for reading text files from a sdcard there is a bug when you select the option "read lines"
    you cannot select how many lines you want to read, it always reads the whole file, which cause a memory fault if you read big files!
    I fixed this in the code (but the software doesn't recognize a EOF anymore..) in CCGByteStreamFileSupport.c
    at row 709 the memory is allocated but it tries to allocate to much (since u only want to read lines).
    looking at the codes it looks like it supposed to allocated 256 for a string:
    Boolean bReadEntireLine = (linemode && (cnt == 0)); 
    if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;    //BUFINCR=256
    but cnt is never false since if you select read lines this is the size of the file!
    the variable linemode is also the size of the file.. STRANGE!
    my solution:
    Boolean bReadEntireLine = (linemode && (cnt > 0));  // ==
     if(bReadEntireLine) {    //if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;
    and now the read line option does work, and reads one line until he sees CR or LF or if the count of 256 is done.
    maybe the code is good but the data link of the vi's to the variables may be not, (cnt and linemode are the size of the file!)
    count should be the number of lines, like chars in char mode.
    linemode should be 0 or 1.
    Hope someone can fix this in the new version!
    greets,
    Wouter
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

    I have another solution, the EOF works with this one.
    the cnt is the bytes that are not read yet, so the first time it tries to read (and allocate 4 MB).
    you only want to say that if it's in line mode and cnt > 256 (BUFINCR) cnt = BUFINCR
    the next time cnt is the value of the bytes that are not read yet, so the old value minus the line (until CR LF) or if cnt (256) is reached.
    with this solution the program does not try to allocate the whole file but for the max of 256.
    in CCGByteStreamFileSupprt.c row 705
     if(linemode && (cnt>BUFINCR)){
       cnt = BUFINCR;
    don't use the count input when using the vi in line mode. count does not make sense, cnt will be the total file size. also the output will be an array.
    linemode seems to be the value of the file size but I checked this and it is just 0 or 1, so this is good
    update: damn it doesn't work!
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

  • Trying to parse a file-read from text file.vi

    I'm attempting to read a txt file that has tab separated data. In the fourth (or any) column is the only data I need. The data is a string of numbers (23.454).
    I've used the Read from Text File.vi and the Read From Spreadsheet.vi and I just don't seem to have enough LV background to extract the pertinent  data into a graph. any suggestions?

    (It is silly to use "delete from array" if all you want is a column. The correct function is "index array")
    Joe's idea above basically works fine. Here's a quick adapdation (the node before the graph is "index array" from the array palette.).
    Message Edited by altenbach on 06-11-2007 11:57 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    FileRead.png ‏11 KB

  • Set a timeout for "read from text file"

    I Need to read from a text file on a remote pc and use the read from text file function to do this. It wotks but sometimes this pc is down causing long wait times in my vi.
    Is there a way to set a timeout for the read from text file function, or is there an other solution?
    Thank you

    You could check that the path is valid first before you attempt to read the file.  hen put the file read in a True-False case structure based on the results of the check.  You can use the function "Check if File or Folder Exists"  It checks whether a file or folder exists on disk at a specified path. This VI works with standard files and folders as well as files in LLB files.   The function is found in the File I/O --> Advanced File Functions palette.
    Tom

  • Read from text file vi won't read file...

    I am very new to LV programming so I hope you forgive any stupid mistakes I am making.   I am using Ver. 8.2 on an XP machine.
    I have a small program that stores small data sets in text files and can update them individually or read and update them all sequentially, sending the data out a USB device.   Currently I am just using two data sets, each in their own small text file.  The delimiter is two commas ",,".
    The program works fine as written when run in the regular programming environment.   I noticed, however, as soon as I built it into a project that the one function where it would read each file sequentially to update both files the read from text file vi would return an empty data set, resulting in blank values being written back into the file.   I read and rewrite the values back to the text file to place the one updated field (price) in it'sproper place.  Each small text file is identified and named with a 4 digit number "ID".   I built it twce, and get the same result.  I also built it into an installer and unfortunately the bug travelled into the installation as well.
    Here is the overall program code in question:
    Here is the reading and parsing subvi:
    If you have any idea at all what could cause this I would really appreciate it!
    Solved!
    Go to Solution.

    Hi Kiauma,
    Dennis beat me to it, but here goes my two cents:
    First of all, it's great to see that you're using error handling - that should make troubleshooting a lot easier.  By any chance, have you observed error 7 when you try to read your files and get an empty data set?  (You've probably seen that error before - it means the file wasn't found)
    If you're seeing that error, the issue probably has something to do with this:
    Relative paths differ in an executable.  This knowledge base document sums it up pretty well. To make matters more confusing, if you ever upgrade to LabVIEW 2009 the whole scheme changes.  Also, because an installer contains the executable, building the installer will always yield the same results.
    Lastly, instead of parsing each set of commas using the "match pattern" function, there's a function called "spreadsheet string to array" (also on the string palette) that does exactly what you're doing, except with one function:
    I hope this is helpful...
    Jim

  • 'read from text file' erases the file

    I am trying to read text in from a text file.  This is the exact code I am using.  For some reason the output from 'read from text file' contains all the text that was originally in the file, but after the code executes the file is empty.  I have several other vi's which use the same code and the file is fine.  But whenever I run this code in this one specific vi the text file gets erased.

    What is in the rest of that "specific vi"? I just tried the code you show, in v2011, and it works as expected, doesn't clear file.
    What version are you running? Can you add an error out, or make sure error output is on in your LabVIEW configuration?
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • Read from Text File - Help Bug?

    Hi - I am currently working on LV8 and I think that there is some misunderstanding potential in the help file. To be more exact in the help to the "Read From Text File" VI.
    The description for "count":
    " ... If count is <0, the function reads the entire file. The
    default is –1, which indicates to read a single line if you placed a checkmark
    next to the Read Lines shortcut menu item and to read the
    entire file if you removed the checkmark next to the item. "
    If count is lower than zero, the function reads the entire file. That sounds clear to me.
    The default is -1, which indicates to read a single line if you placed a checkmark next to the "Read Lines" shortcut menu item. Now what? Does it read a single line or the whole file?
    .. and to read the entire file if you removed the checkmark next to the item. I thought it reads the whole file if I use -1 ?
    the VI itself behaves as I'd expect it to:
    * If I place a checkmark next to Read Lines and put -1, I get an array containing the lines
    * If I remove the checkmark, I get only a single string item.
    Now where is the error? Is the VI not working properly or only the description a little bit ... strange ?

    ?hein??
    ?what?
    Both you guys lost me..
    And I drink coffee without sugar (being sweet enough, already) 
    Here is what I get from Context Help on the Read From Text File:
    Read from Text File
    Reads a specified number of characters or lines from a byte stream file. By default, this function reads all characters from the text file. Wire an integer value to count to specify how many individual characters you want to read starting with the first character. Right-click the function and place a checkmark next to the Read Lines option in the shortcut menu to read individual lines from the text file. When you select the Read Lines option in the shortcut menu, wire an integer value to the count input to specify how many individual lines you want to read from the file starting with the first line. Enter a value of -1 in count to read all characters and lines from the text file.
    Humm.
    New feature (again)..  If you select checkmark the Read Lines option, it will not send the text to a sting indicator, as shown in the attached image.  If selected, then it's expecting to write lines to an array of strings...  WHY???  I don't know..  I'll ask..
    Strange...  LV8 is full of mysteries... 
    RayR
    Attachments:
    bad write file.JPG ‏33 KB
    more bad write file.JPG ‏12 KB

  • Read from Text File Detailed Help need Clean-up

    This is probably well known and nobody has bothered fixing it but the detailed Help of the "Read from Text File" function is sort of ambiguous:
    -  statement 1: refnum out is the refnum of the file that the function read. You can wire this output to another file function, depending on what you want to do with the file. The default is to close the file if it is referenced by a file path or selected from the file dialog box. If file is a refnum or if you wire refnum out to another function, LabVIEW assumes that the file is still in use until you close it.
    - statement 2: If you wire a path to file, the function opens the file before reading from it and closes it afterwards.
    I have found statement 1 to be correct, which makes statement 2 incomplete (and sort of tautological in the sense that 1) you expect LabVIEW to open the file before reading from it if you provide a path instead of a refnum... and 2) if you use a path input to file AND use the refnum out for some other function, the file is NOT closed, as correctly stated in statement 1).
    Just sayin' ...

    X,
    It deeply concerns me that you would take my response to mean indifference. I certainly had no intention to belittle what you had to say. On the contrary, I took this up with the concerned team, and had a small discussion. If you say that what someone says on this forum is of lesser or no value to National Instruments, you could not be more wrong. It defeats the whole purpose of this public forum.
    My point was not that it is not an issue, it certainly seems to be. Please be rest assured that even if it does not look like it from the outside, each comment however big or small is taken back to our workplaces and some thoughts poured over it. 
    On the whole, I recognise that I had a role to play in this misunderstanding of tone, and I sincerely apologise.
    Warm Regards,
    Prashanth N
    National Instruments

Maybe you are looking for

  • Can I put Chinese and English characters in the same dynamic text box?

    I'm translating a game into several different languages, one of which is Chinese. I've noticed that in a dynamic text box where English characters are included also, they aren't displayed when the .swf is exported. The font is embedded in the documen

  • An error occurred while trying to add printer

    when i try to add my usb connected hp deskjet f4135 all-in-one printer from my available list i get an error message "client=error-request-value-too-long" Please can anybody tell me what im doing wrong Message was edited by: evilways

  • I am no longer able to rotate drawing markups

    I am no longer able to rotate drawing markups - I am using Acrobat X 10.1.4. What happened to this function of drawing markups such as circles, lines, squares?

  • Oracle8 oci

    Hello, I need to connect from php to an old oracle8i database (8.1.6). I used the old php_oracle.dll extension witch is no longer supported. I want to use some new features in the php_oci8.dll extensions like oci_bind_by_name. The problem is that I h

  • Geolocation for Android With Adobe Content Viewer

    Hello guys, I'm working at a project using HTML5 features to turn it an interesting application, but, when I use the geolocation with Google Maps anything happen :/ do you know why it doesn't working? Thanks so much.