Help with Read/Write File

hi I was wondering if someone can help me do some read/write file with java. here is what I want to do:
Read a file and search the whole file for a word such as "throw" and print out the rest of that line to a new file. in the case of "throw", i want to link all thrown exceptions to the file that contained them.
can someone help me out and let me know what way I can approach in this?
any help would be greatly appreciated.
thanks!

Rough and dirty, here's a class that will read a file and return a resultset:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.util.*;
import java.text.DateFormat;
public class Utils{
     File fileName;
     FileOutputStream outputFile;
     boolean closeChannel;
     //Constructor
     public Utils(String directory, String filename){
          String strFileDir = directory;
          String strFileName = filename;          
          File fileDir = new File(strFileDir);
          fileName = new File(fileDir, strFileName);
          // If directory does not exhist, create it.
          if(!fileDir.isDirectory()){
               if(fileDir.mkdirs()){
                    System.out.println(fileDir + " created.");
               else{
                    System.out.println(fileDir + " could not be created.");                    
public ArrayList readText() throws IOException{          
          // Read content of file into a collection
          ArrayList arrayList = new ArrayList();
          try{
               BufferedReader in = new BufferedReader(new FileReader(fileName));
               String line;
               while((line = in.readLine()) != null){
                    arrayList.add(line);
               in.close();               
          catch (IOException ex){
               throw ex;
          return arrayList;          
     }And here's how you use the class:
// Create a new Disk Utilities object.  This can be used for all subsequent read/writes to this file.
          Utils utilTest = new Utils("e:/testing", "Testing.txt");
// Create a collection to hold the data from the file.
          ArrayList arrayList = new ArrayList();
          try{arrayList = utilTest.readText();}catch(IOException ex){ex.printStackTrace(System.err);}

Similar Messages

  • Need help with read/write to MODBUS RTU registers in Labview 8.0

    I’m trying to write and read the registers in G3800xx016. controlling temperatures and lightning.  Please look at the attached pdf file for this unit..
    I have used Lookout for about three years, and it works fine.. Now I want to expand my system and try to use Labview 8.0
    My temperature register start adress is 100 Hex  (256 dec) I read from Register with Function code 03.
    This register have values from 0-255 witch mean in labview for me as unsigned byte U8
    I read my temperature from the register like this: eks.: 40257 lets say value=5
    Slave    FC       Start Adress     Byte     Value               CRC
    01        03        0100                02        0005                7847   
    This is the status received from the Modbus tester when I use null-modem connection..
    I receive the same value if I use Modscan32
    I have used null-modem cable to read out the values.
    I have also PIR detectors that control movements and light of and on, and I read these starts at 40017.1
    01   03     0010     02    
    The register to switch on and of heating and lights starts at 404097.1  FC16  
    Values mention here is read from Lookout 5.0  
    I have tried examples and read for weeks about this, but everything stops when I try to use Labview 8.0    I can’t read any values from my Master unit, neither write to it, or read any values in Modbus testers when I use null-modem cable.. I have tried different baud rates in my serial connection and it works perfect in Lookout, but Not Labview..
    I have even bought DSC module, but I can’t write to either com ports or Modbus testers..
    Please anybody… is there anybody that can give me help with this??
    Start address for for PIR detectors is 40017.1 (FC03)  and for writing bits for on of to light and heatsystem is 404097.1 (FC16)
    I would be very happy for any idea that can give me some positive results…  Look at the attached pdf file.
    Thanks.. and very best regards from
    Benjii…
    Attachments:
    G3800x016_02-2005_eng.pdf ‏70 KB

    Hi... and thanks for your answer..
    Yes, I have downloaded the NI Modbus drivers.. I have downloaded that one + a lot of other things about Modbus..
    I have also tried communication between lokout and labview true null-modem cable.. and it works..
    I have tried several Modbus examples and I communicate with most of them with null-modem cable.
    I write to the right registers as well, cause I use Modbus scanner to read the information..
    I have used the same settings for serial communication as my Master device use, bust still I can't get any response..
    There was an error message in one of my example from the Modbus INIT module.. Maybe I should try to set up a new connection using VISA ??
    Maybe the problem is to INIT my serial port? I have tried restarting my computer after closing my system..  But still, I have the same problem..
    I hope you can give me any idea...
    Thanks again..  by the way.. is it possible to write and read directly to serial port with the DSC module??  If so.. how?? 
    Very best regards..
    Benjii..

  • Need help with reading a file

    Hello, I'm trying to read this file, but I keep getting a java.nullpointerexception at the end of it:
    Element: PART
    Content: (HEADER,CHAPTER+)
    Element: p
    Content: (#PCDATA)
    Element: INTRODUCTION
    Content: (HEADER,p+)+
    Element: CHAPTER_NUMBER
    Content: (#PCDATA)
    Element: HEADER
    Content: (#PCDATA)
    Element: BOOK
    Content: (OPENER,SUBTITLE?,INTRODUCTION?,(SECTION|PART)+)
    Element: SECTION
    Content: (HEADER,p+)
    Element: CHAPTER
    Content: (CHAPTER_NUMBER,CHAPTER_TEXT)
    Element: OPENER
    Content: (TITLE_TEXT)*
    Element: CHAPTER_TEXT
    Content: (p)+
    Element: SUBTITLE
    Content: (#PCDATA)
    Element: TITLE_TEXT
    Content: (#PCDATA)
    here is my code:
                           s = br.readLine();
                            while (s != null){
                                    node[i] = new Node();
                                    if (s.startsWith("Element: ")){
                                       node.element = s.substring(s.indexOf(":") + 2);
    System.out.println("Element[" + i + "]: " + node[i].element);
    else if (s.startsWith(" Content: ")){  
    node[i].content = s.substring(s.indexOf(":") + 2);
    System.out.println("Content[" + i + "]: " + node[i].content);
    s = br.readLine();
    if (s.startsWith("Element: ")) i++; //line 194 causes error
    br.close();
    here is my output
    Element[0]: PART
    Content[0]: (HEADER,CHAPTER+)
    Element[1]: p
    Content[1]: (#PCDATA)
    Element[2]: INTRODUCTION
    Content[2]: (HEADER,p+)+
    Element[3]: CHAPTER_NUMBER
    Content[3]: (#PCDATA)
    Element[4]: HEADER
    Content[4]: (#PCDATA)
    Element[5]: BOOK
    Content[5]: (OPENER,SUBTITLE?,INTRODUCTION?,(SECTION|PART)+)
    Element[6]: SECTION
    Content[6]: (HEADER,p+)
    Element[7]: CHAPTER
    Content[7]: (CHAPTER_NUMBER,CHAPTER_TEXT)
    Element[8]: OPENER
    Content[8]: (TITLE_TEXT)*
    Element[9]: CHAPTER_TEXT
    Content[9]: (p)+
    Element[10]: SUBTITLE
    Content[10]: (#PCDATA)
    Element[11]: TITLE_TEXT
    Content[11]: (#PCDATA)
    java.lang.NullPointerException
    at Test.readDTDObjectFile(Test.java:194)
    at Test.<init>(Test.java:143)
    at Test.main(Test.java:338)
    can anybody help me figure out how to fix this? thanks so much!

    nevermind, i figured it out. thanks anyway!

  • Help with reading XML file

    Hi,
    I have a piece of code:
    import org.w3c.dom.Document;
    import javax.xml.parsers.DocumentBuilder;
    import org.apache.commons.httpclient.HttpMethod;
        private Document xmlDoc;
        private DocumentBuilder docBuilder;
        private HttpMethod method;
        xmlDoc = docBuilder.parse (method.getResponseBodyAsStream());When I execute the last line, I get a nullPointerException. I know that my method is instantiated.
        System.out.println ("MyRssReader.readRSSFeed: method==null? " + (method==null) );gave:
    MyRssReader.readRSSFeed: method==null? falseSo, the big question is, what is not instantiated? I know that X in
    docBuilder.parse (X);can be a File, (abstract) InputSource, InputStream (as I am using), InputStream with URI, or URI. URI in both cases as String.
    I can get the RSS feed as a String, but see no way to get that String parsed.
    Abel
    PS: I also tried
    xmlDoc = docBuilder.parse (method.getURI().toString());and
    xmlDoc = docBuilder.parse (method.getResponseBodyAsStream(), method.getURI().toString());EDIT:
    Reading the parse method in DocumentBuilder I see it checks if the InputStream is null. When it is null, it raises a
    new IllegalArgumentException("InputStream cannot be null");As I do not see that exception, the InputStream is instantiated.
    Edited by: Abel on Jan 31, 2008 9:46 AM
    Added part about DocumentBuilder.parse(InputStream is)

    The stack trace I got is:
    Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
         at foo.bar.rssreader.RssReader.readRSSFeed(RssReader.java:111)
         at foo.bar.MyModel.createFeed(MyModel.java:106)
         at foo.bar.MyModel.setLoggedIn(MyModel.java:89)
         at foo.bar.window.LogInPanel.checkFieldsAndLogIn(LogInPanel.java:297)
         at foo.bar.window.LogInPanel.actionPerformed(LogInPanel.java:211)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • I need help with a PDF file that is an image, the "Read Out Loud' option does not work, please help!

    I need help with a PDF file that is an image, the "Read Out Loud' option does not work, please help!

    You mean an image such as a scanned document?
    If that is the case, the file doesn't contain any text for Reader Out Loud to read. In order to fix that, you would need an application such as Adobe Acrobat that does Optical Character Recognition to convert the images to actual text.
    You can also try to export the file as a Word document or something else using ExportPDF which I believe offers OCR and is cheaper than Acrobat.

  • Deliver file with read/write properties on target side using receiver file

    Hi All,
    Our file-to-file scenario works fine. By default, PI creates file on target directory with the 644 permissions. Files coming inbound from PI are not read/writable to the group. Currently the files from PI are coming across with 644 permissions and they should be 664 or 660. Is there a way to generate read/write files on targer side using SAP PI??
    Thanks in advance,
    - Riya Patil

    Hello,
    Try using Run-Operating system command after processing parameter with the below mentioned command:
    chmod 0755 /usr/sap/tmp/test/*
    where:  /usr/sap/tmp/test/ is the directory path location.
    Br,
    Rahul

  • IO Operation (read/write files) in IPAD AIR downgrade ~50% than the one in IPAD4

    Summary:
    UnZip the same file with the same native unzip method (native zlib) in IOS7, ipad air take +50% more time consumption than the one in iPAD4.
    for unZip, it main perform the IO read/write files in ipad, does apple air already changes the file system ?
    Steps to Reproduce:
    UnZIP a file with native zlip on both ipad AIR and IPAD 4 :
    IPAD AIR: 16GB
    IPAD 4: 16GB
    ZIP file size: 700KB
    Files in zip file: 225 files (120 files are images)
      after remove the images, the time on IPAD AIR will save 50% time consumption
    unZip method: the native zlib
    unzip time on IPAD AIR+ IOS7: ~1200ms
    unzip time on IPAD 4+ IOS7: ~800ms
    Expected Results:
    The unzip time should be almost the same on IPAD AIR and IPAD4.
    Actual Results:
    For same IO operation read/write file, IPAD AIR gets the 50% downgrade performance than the one in IPAD4
    Version:
    IPAD4: 16GB WIFI + IOS7
    IPAD AIR: 16GB WIFI + IOS7
    does anyone else encounter the same problem ?
    A bug already submitted for apple: https://devforums.apple.com/message/993060

    I even tried porting the code to Gumbo and running it there - still, no fonts are being enumerated.
    If you're too lazy to read the whole above post, here's the problem in one sentence
    An SWF that contains a textfield with embedded fonts, when launched by itself succeeds to return the embedded font using Font.enumerateFonts(false), however when loaded using Loader.loadBytes into AIR, it fails to see those fonts even though the textfield in it is displayed and editable.
    How do I make the loaded child application and AIR see the embedded font?

  • Problem with reading config file

    Hello,
    I have problem with reading config file from the same dir as class is. Situation is:
    I have servlet which working with DB, and in confing file (config.pirms) are all info about connection (drivers, users, passw, etc.). Everything work fine if I hardcoded like:
    configFileName = "C:\\config.pirms";I need to avoid such hardcoding, I tryied to use:
    configFileName = Pirms.class.getClassLoader().getResourceAsStream ("/prj/config.pirms").toString();but it isn't work.
    My config file is in the same directory as Pirms.class (C:\apache-tomcat-5.5.17\webapps\ROOT\WEB-INF\classes\prj)
    Also I tryied BundledResources, it isn't work fo me also.
    Can anybody help me to solve this problem? with any examples or other stuff?
    Thanks in advance.
    Andrew

    Thanks, but I am getting error that "non-static method getServletConfig() cannot be referenced from a static context"
    Maybe is it possibility to use <init-param> into web.xml file like:
    <init-param>
      <param-name>configFile</param-name>
      <param-value>/prj/config.pirms</param-value>
    </init-param>If yes can anybody explain how to do that?
    I need to have that file for:
    FileReader readFile = new FileReader(configFile);Thanks in advance.

  • How to read write file in HTML5 extension

    Hi,
    I think it could be very generic question since moving from Flex to HTML5 extension is loosing ability to read write a file in local file system.
    I'm trying to write a log file within extension space but It throws error as 'TypeError: Illegal constructor'
    new File(csInterface.getSystemPath(SystemPath.EXTENSION)+"/log/Log_"+.getCurrentDateString+".txt");
    does someone have solve for this.
    Thanks in advance
    MM

    Yeah, It could be a reason for nested error but I got the error right before executing "getCurrentDateString". But I kind of figured it out as Javascript looses ability to read write file in user file system except Crome browser, you can read more here. However Adobe has added fs API within CEP which allows user to read and write file in user system.
    Here is some peace of code on how to do it, complete API reference check here :
    var result = window.cep.fs.writeFile(logFilepath, "Your data goes here");
      if(result.err != 0)
      throw new Error("Result object has error");
    However still this does not provide any method to append the content in existing file as a result if you wanted to write kind of log file, every time you need to first read the file and then concatenate your content to file data then write data again to new file. sound hefty to append content?
    I'm hoping if any Adobe staff has any comment on this.
    Thanks
    MM

  • I need a help in reading video file of 80MB into ...

    Hello,
    I need a help in reading video file of 80MB into a vector storing ByteArrays in it.Please help me soon.
    Thank You

    Hello,
    I was able to solve my problem by thinking & my code goes as follows.I am trying to read a video file in my program.
    public Vector getFileMediaContent(RandomAccessFile fileObj){
         Runtime runtime = Runtime.getRuntime();
    System.out.println ("Free memory : inside Boolean Type Panel" + runtime.freeMemory() );
    dataContent.removeAllElements();
    System.out.println("dataContent :"+dataContent.size());
    try{
    int size=(int)fileObj.length();
    if(size<2000000){
    byte[] data = new byte[size];
    fileObj.read(data);
    dataContent.addElement(data);
    data=null;
    System.gc();
    else{
    int fixedsize=2000000;
    int startindex=0;
    int read=0;
    int remaining=0;
    while(read!=-1){
    byte[] data=new byte[fixedsize];
    read=fileObj.read(data,0,data.length);
    dataContent.addElement(data);
    startindex=startindex+data.length;
    remaining=size-startindex;
    fileObj.seek(startindex);
    data=null;
    System.gc();
    if(remaining>0 && remaining<2000000){
    byte[] data1=new byte[remaining];
    read=fileObj.read(data1,0,data1.length);
    dataContent.addElement(data1);
    data1=null;
    System.gc();
    System.out.println("outside while");
    System.out.println("dataContent 1 :"+dataContent.size());
    System.out.println ("Free memory : inside Boolean Type Panel" + runtime.freeMemory() );
    fileObj = null;
    System.gc();
    }catch(Exception e){
    e.printStackTrace();
    return dataContent;
    Now I am not facing the problem of IndexOut of Bounds Exception But I am getting Out of Memory Error.
    Can You suggest me to come out of this,.
    As I know I have two solutions.
    1.Make the objects Null which is using more space & call System.gc();
    2.Increase the Virtual Memory of my System.
    Any solutions other than this?
    And How to Increase the Virtual Memory?Please do reply.
    ThankYou

  • How To read/write file on remote server in java

    Hi All,
    How To read/write file on remote server in java? I mean using URL - http://www.xyz.com can I right file to that perticular server.
    Thanks in advance

    If your server support a means of uploading files you can.
    A popular means is [http://en.wikipedia.org/wiki/WebDAV]
    However, by default web server don't allow you upload files, its usually something you need to configure or install.
    I suggest you have a look at your web servers documentation.

  • Help with utl_file (read/write file from local directory)

    Need help reading/writing file on local machine from plsql using 10.2 DB.
    I am trying to read/write a file from a local directory(laptop) without success.
    I have been able to read/write to the database server directory but can't write to directory on local machine.
    The utl_file_dir parm has been set to * and the db restarted but I can't get it to work... Here's the plsql statement.
    out_file := UTL_FILE.FOPEN ( 'C:\PLSQL', 'TEST.TXT', 'W' ,32767);
    Whenever I run it continues to write to c:\PLSQL dir on the database server. Have looked at the "Directory" object and created MY_DIR = C:\PLSQL but it writes to the db server.
    Running 10.2 on a remote windows server, running PLSQL using sql*navigator.
    Thanks in advance for your help..

    I don't see how you expect the server to be able to see your laptop across the network, hack into it and start writing files. Even if it could, what if there is more than one laptop with a C: drive? How would it know which one to write to?
    Is there a shared drive on the server you can access via the laptop?

  • How to create files with read/write privileges for everyone?

    I have two iMacs 7,1 (one with Snow Leopard and the other with Mountain Lion) in a local area wireless network.
    I have shared the "documents" folder in the Snow Leopard iMac in order to have files available to the other iMac. The folder has read/write privileges for everyone.
    When I create a new file in the shared "Documents" folder (for example a new Open office document, or a Keynote presentation) this file is by default "read/write" for the Administrator but only "read" for all the other users, so when I try to open it from the other iMac, I am informed that the file is "read only".
    I can obviously change the privileges of the file in the information window, but I have to do on a file per file basis and this takes too long.
    Is it possible to change settings in order to create files which are always "read/write" for everyone?
    And, secondly, since I have several existing files whose privileges I should manually change one by one, is it possible to make global changes of their privileges?
    Thanks in advance
    Best regards

    couple of different changes - 1st, if you want to share folders, doing your whole documents folder is not the best way.  Since both your computers can handle AidDrop, that's what I would recommend - http://osxdaily.com/2011/11/14/how-to-use-airdrop-in-mac-os-x/ - as it create an instant Ad-Hoc network between the two computers and then let's it done. 
    A second possibility that may not be what you're looking for, is to use google drive or some similay cloud sharing app to sync the documents back and forth.  both of these solutions will transfer the files well, but the airdrop may be simplest

  • Need help with "reading" files ...

    Okay, here's the scoop in two versions ...
    The Short and Sweet:
    I'm VERY new to Java programming, but before I dedicate a lot of time into my project, I need to know first if it is possible for a java.class applet (running in a browser, online) to read from a text file located on the (remote) server - ie: the same server and path as the java.class applet is located.
    The Long and Confusing:
    The primary objective is to recursively read from a constantly changing data/text file (generated by a php script), then "parse" that data into certain variables which in turn affect the (browser) output viewed by the visitor. A simplified example of this would be to capture x-y coordinates generated by a perpetually running php script (via a "shared" text file), then the applet would use this "read" data to constantly update the x-y positions of two (or more) graphical objects within the running applet.
    Hope this makes sense. I'm not asking anybody to actually code this for me (though an example would be nice) ... I really just need to know if it can be done before delving into this somewhat paramount project. Thanks.
    --Mikey

    The Short and Sweet:
    I'm VERY new to Java programming, but before I
    dedicate a lot of time into my project, I need to know
    first if it is possible for a java.class applet
    (running in a browser, online) to read from a text
    file located on the (remote) server - ie: the same
    server and path as the java.class applet is located.
    It is possible to use an Applet to read a file from the server, but you need to use a URL stream, not a file stream because of the Applet security constraints. Applet.getCodeBase() will return the URL of the directory where the Applet is. You can use the URL to create a URL to the file. Then read the new URL's InputStream.

  • Need help with reading a midi file!!!

    I want to be able to make a java program that can read midi files. I need to know what notes are played and when. how can i do this.
    A bit of code would be nice to to use as a resource.
    thnx

    http://java.sun.com/products/java-media/sound/
    There are links to code samples and maybe a tutorial

Maybe you are looking for

  • Color issue only with finder on a dell U2410 screen

    Hello... I've got a macbookpro 15' with snow leopard. I've just connected a second display screen (DELL U2410) through a mini display to DVI adapter. On te Dell, when i look a photo in the finder/cover flow, the reds are satured. And when i look the

  • ADF: Creating DataControl from POJO model

    HI I am new the ADF, i created simple java code in ADF Model (Jdeveloper 11.1.1.1)and exposed as a DataContol( Right Click on javafile -> Create Data Control). jdeveloper creates Datacontrol and XML file (HelloWorld.xml). for a same code i did in Jde

  • Lightroom, PS, Bridge, Raw, --I have all of these, do I need Lightroom?

    With all of these programs, why do I need to get involved with Lightroom for my photos? What makes Lightroom different?

  • Mapping Packing Qty with Oracle

    Hi, Kindly help me in solving the below requirement. 1) Item A is a buy part. 2) Fixed Order Qty = 650 pcs 3) Packing qty of each box = 25 pcs If the net requirement for the item A is below fixed order qty,then the suggestion would be the fixed order

  • Report to Report - Web Application Designer

    I have created a simple template using BEx Web Application Designer. The Query I've picked is set up with receiver reports. e.g. I want to do a report to report interface from the data in my template to another query and another template. However whe