How to browse a file and extract its contents

i want to browse a file and extract its contents.My code is given below but its not working .Can anybody help me please
JFileChooser fc = new JFileChooser();
          int returnVal = fc.showOpenDialog(jfrm);
          if (returnVal == JFileChooser.APPROVE_OPTION)
          File file = fc.getSelectedFile();
          //This is where a real application would open the file.
          fileName=file.getName();
          //This is a file function to extract data from a file.
          //It reads data from a file that can be viewed on cmd
          jlab3.setText(fileName);
          try
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Convert our input stream to a
// DataInputStream
          DataInputStream in =new DataInputStream(fstream);
// Continue to read lines while
// there are still some left to read
// while (in.available() !=0)
// Print file line to screen
          fileName1=in.readLine();
          jlab3.setText(fileName1);
          in.close();
catch (Exception e)
          System.err.println("File input error");
          }

JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(jfrm);
if (returnVal == JFileChooser.APPROVE_OPTION)
File file = fc.getSelectedFile();
//This is where a real application would open the file.
fileName=file.getName();
//This is a file function to extract data from a file.
//It reads data from a file that can be viewed on cmd
jlab3.setText(fileName);
try
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Convert our input stream to a
// DataInputStream
DataInputStream in =new DataInputStream(fstream);
// Continue to read lines while
// there are still some left to read
// while (in.available() !=0)
// Print file line to screenHere you are reading the first line of the file
  fileName1=in.readLine();
//}and here you are displaying the line in a (I suppose) JLabel. A JLabel is not very suitable for displaying a file content, except is the file contain few characters !!!
jlab3.setText(fileName1);
in.close();
catch (Exception e)
System.err.println("File input error");
}If you want to read the complete file content you must uncomment lines inside while instruction, like this
while (in.available() > 0) {  // I prefer to test in.available like this, instead of !=
  // append text to a StringBuffer (variable named sb here) or directly in a textarea.
  sb.append(in.readLine());
...

Similar Messages

  • How to create a file and store its contents into another file?

    Hi,
    I'm having some trouble trying to create a code where I have to to create a file and store its contents into another file?
    I read the API, but I'm not certain how this file thing works.
    Here's my code so far:
    public static void main(String[] args) throws Exception
              File file = new File("tasks.txt");
              if (file.exists())
                   System.out.println("File already exists");
                   System.exit(0);
              Scanner scan = new Scanner(System.in);
              Scanner scan2 = new Scanner(System.in);
              //Scans the input line by line
              scan.useDelimiter("\\n");
              //Scans the input by tabs
              scan2.useDelimiter("\\t");
              PrintWriter outputs = new PrintWriter("newtasks.txt");
              outputs.print("ok");
              outputs.println(3);
              outputs.close();
         }

    I managed to change my text into uppercase, but how do I store the uppercase content into another file.
    -So this is what I did so far, I took a text file and modified its strings to uppercase.
    -Now I need to put those modified strings into another text file, is there a way where I can do that with my current code?
    -I already tried printwriter, but it doesn't seem to work
    public static void main(String[] args)throws IOException
              //Task[] oneHundredTasks = new Task[100];
              String uppercase;
              String combine;
              Scanner scan = null;
              FileInputStream in = null;
            FileOutputStream out = null;
            PrintWriter output = null;
            try
                 scan = new Scanner(new BufferedReader(new FileReader("tasks.txt")));
                 scan.useDelimiter("\\n");
                 scan.useDelimiter("\\t");
                while (scan.hasNext())
                     if(!scan.hasNext())
                          scan.next();
                     combine = scan.next();
                     uppercase = combine.toUpperCase();
                     System.out.println(uppercase);
            finally
                if (scan != null)
                    scan.close();
            //The program will try the input and output files
            try
                 in = new FileInputStream("tasks.txt");
                out = new FileOutputStream("newtasks.txt");
                int c;
                //The number "-1" is used to indicate that it has reached the end of the stream.
                while ((c = in.read()) != -1)
                    out.write(c);
            finally
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
         }

  • Accessing a file and reading its contents.

    Hi all,
    I created a Portal Application to access a file and display its contents in an iView .
    But it showing the exception like "File Not Found".
    In simple java application i could able to get the result. In portal application i couldn't .
    I have given the full path of the file location.
    I need a help regarding this?
    Regards,
    Eben

    IS the file on the portal server? It must be visible to the service user that runs the Java engine...

  • Can a servlet read a jsp file and display its contents?

    Hi,
    I would like to know if Servlets can read a Jsp file and display its contents.. Right now for our website, I am using a html file to be displayed after a successful post operation through the Servlets...
    -Thanks!

    I posted this in another thread.
    Here's some code that reads using a URL. This doesn't work with JSPs as the server executes JSP when it connects but it's useful for other file types. Note that the filename is a URI</h1>This is <code>show.jsp</code></h1>
    <hr>
    <%! String file = null; %>
    <%! java.io.InputStream is = null; %>
    <%
    file = request.getParameterValues("filename")[0];
    try {
       is = (new java.net.URL(file)).openStream();
    } catch (java.io.IOException ioe) { out.write(file + " not found!<br>"); }
    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line = "";
    %>
    <pre>
    <%
    while((line = in.readLine()) != null) {
    %>
    <%=line%>
    <%
    %>
    </pre>

  • Upload 2 files and compare its contents

    Hi guys,
    I want to upload 2 files in SAP and compare its contents.
    How am i going to do that?
    Please provide sample code... Thanks a lot!
    rgds,
    Mark

    Hi Mark,
    I expected to use this code, once u can try this code.
      OPEN DATASET lv_filename FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
      IF sy-subrc = 0.
        LOOP AT gi_output1 INTO gwa_output1.
          CLEAR lv_string.
          CONCATENATE gwa_output1-matnr
                      gwa_output1-maktx
                      gwa_output1-werks
                      gwa_output1-bmeng
                      gwa_output1-posnr
                      gwa_output1-idnrk
                      gwa_output1-ojtxp
                      gwa_output1-mngko
                      gwa_output1-mmein
                      gwa_output1-flag
                      INTO lv_string
                      SEPARATED BY cl_abap_char_utilities=>horizontal_tab.
          TRANSFER lv_string TO lv_filename.
          IF sy-subrc <> 0.
            MESSAGE e006(zpdm).
          ENDIF.              "if sy-subrc <> 0.
        ENDLOOP.
         OPEN DATASET lv_filename FOR appending IN TEXT MODE ENCODING DEFAULT.
      IF gi_output2[] is not initial.
        LOOP AT gi_output2 INTO gwa_output2.
          CLEAR lv_string.
          CONCATENATE gwa_output2-matnr
                      gwa_output2-ojtxb
                      gwa_output2-werks
                      gwa_output2-bmeng
                      gwa_output2-posnr
                      gwa_output2-idnrk
                      gwa_output2-ojtxp
                      gwa_output2-mngko
                      gwa_output2-mmein
                      gwa_output2-flag
                INTO  lv_string
           SEPARATED BY cl_abap_char_utilities=>horizontal_tab.
          TRANSFER lv_string TO lv_filename.
          IF sy-subrc <> 0.
            MESSAGE e007(zpdm). " WITH text-006.
          ENDIF.           "if sy-subrc <> 0.
        ENDLOOP.
      ENDIF.

  • How To read lib*.so files and verbose its content

    Hi
    Is there any command with which we can read shared library files and see whats its contents are i.e. whats are the functions available inside it and how its control flow.
    Regards
    Jeet

    I know of none that shows flow control but you can do a man against nm(1) to see what is in the library (nm libc.so.1).

  • How to read a file and save the contents into array list

    i have textfile contains information like:
    Name: James Smith
    Customer no: 663,282
    Post code: BA1 74E
    Telephone no: 028-372632
    Last modified: Feb 10, 2008 6:50:00 PM GMT
    Name: Janet Smith
    Customer no: 663,283
    Post code: BA1 74E
    Telephone no: 028-372632
    Last modified: Jan 11, 2007 8:10:05 PM GMT
    etc...
    how can i read the contents of this textfile and put the data into an ArrayList called ArrayList<Customer> customerList.
    i knew that i need two classes, one for CustomerDetails and one for ReadFile.
    i have already done the customer class as:
    import java.util.Date;
    public class Customer
        String Name;
        int CustomerNo;
        String Postcode;
        String teleNo;
        Date lastModified;
        public Customer(String Name, int CustomerNo, String Postcode, String teleNo, Date lastModified)
         assign(Name, CustomerNo, Postcode, teleNo, lastModified);
        public void assign(String Name, int CustomerNo, String Postcode, String teleNo, Date lastModified)
         this.Name=Name;
         this.CustomerNo=CustomerNo;
         this.Postcode=Postcode;
         this.teleNo=teleNo;
         this.lastModified=lastModified;
        public String toString()
         String allDetails = "Name: "+Name+
             ", Customer No: "+CustomerNo+
             ", Postcode:"+Postcode+
             ", Telephone No: "+teleNo+
             ", Last Modified Date: "+lastModified;
         return allDetails;
    }i just wondering how can i code the ReadFile class?
    can anyone help me please. thank you in advance.

    thank you for your suggestion, but i have already started to code the readCustomer class using the Scanner.
    the code i got so far is:
    import java.util.Scanner;
    import java.io.*;
    public class readCustomer
        public static void main(String[] args)
         readCustomer("Customers.txt");
        public static void readCustomer(String filename)
         try {
             Scanner scanner = new Scanner(new File(filename));
             scanner.useDelimiter(System.getProperty("line.separator"));
             while (scanner.hasNext()) {
              processLine(scanner.next());
             scanner.close();
         } catch (FileNotFoundException e) {
             e.printStackTrace();
        public static void processLine(String line)
         Scanner scanner2 = new Scanner(line);
         scanner2.useDelimiter("\\s*:\\s*");
         String description = scanner2.next();
    *// here is where i am struggling. i don't know how to get the information after the : sign*   
    }i am currently struggling with the processLine method?
    also, i am not sure how to group a set of information and put them into the arraylist.
    Any hint, please. Thank you.
    Edited by: mujingyue on Feb 26, 2008 12:42 PM

  • How do I uninstall iphoto and all its contents and then reinstall?

    For the last few years i have been deleting my photos from iphoto incorrectly which has resulted in many modified versions which has clogged up my HD, so i want to completely uninstall my whole iphoto application, before i reinstall it.
    if you could tell me how to do that, that would be great
    cheers
    j

    Welcome to the Apple Discussions.
    Removing the application and re-installing it will not solve the problem you describe:
    i have been deleting my photos from iphoto incorrectly which has resulted in many modified versions which has clogged up my HD
    That's a Library issue. The library is quite separate from the application.
    If you have unattached modifieds then I would suggest that you don't need to start over, but rather use iPhoto Library Manager to rebuild the Library. This will create a new Library preserving much of the work you've already done - albums and wanted edited versions and so on, and leave behind the unattached files. Then you can trash that old Library.
    If you really want to slash and burn:
    To create and populate a new *iPhoto 09* library:
    Note this will give you a working library with the same pictures as before, however, you will lose your albums, keywords, modified versions, books, calendars etc.
    In the iPhoto Preferences -> Events Uncheck the box at 'Imported Items from the Finder'
    Move the iPhoto Library to the desktop
    Launch iPhoto. It will ask if you wish to create a new Library. Say Yes.
    Go into the iPhoto Library (Right Click -> Show Package Contents) on your desktop and find the Originals folder. From the Originals folder drag the individual Event Folders to the iPhoto Window and it will recreate them in the new library.
    When you're sure all is well you can delete the iPhoto Library on your desktop.
    Regards
    TD

  • I need help. My ipad 2 was stuck in recovery mode. i tried to connect it to itunes and restore but after downloading the file and extracting the software there is a pop up message that says "the device is full" i dont know what to do. Its been 2 days now.

    I need help. My ipad 2 was stuck in recovery mode. i tried to connect it to itunes and restore but after downloading the file and extracting the software there is a pop up message that says "the device is full. Deleting files and emptying your recycle been will help you restore." how am i going to erase files if i can't open my ipad. i dont know what to do. Its been 2 days now. please help. thanks.

    yes i am sure. This are the exact words... "The iPad "iPad" could not be restored. The disk you are attempting to use is full. (Removing files and emptying the recycle bin will free up additional space". i tried some options, hard reset, redsnow, tinyumbrella but still it's stuck.

  • How to make an openfiledialog? (browse a file and put it in a parameter)

    How to make an openfiledialog? (browse a file and put it in a parameter)
    Best Regards

    hi,
    check the code  below:
    FORM sub_gui_download.
    * Define local variables
      DATA:
        lo_fullpath       TYPE string,
        lo_filename       TYPE string,
        lo_path           TYPE string,
        lo_user_action    TYPE i,
        lo_encoding       TYPE abap_encoding.
    * Define local constants
      CONSTANTS:
        lc_encoding(1) TYPE c VALUE 'X',
        lc_directory TYPE string VALUE 'D:',
        lc_filetype TYPE char10 VALUE 'DAT',
        lc_separator TYPE char01 VALUE 'X',
        lc_blank TYPE char01 VALUE ''.
    * Call method to create dynamic save_path and save_format
      CALL METHOD cl_gui_frontend_services=>file_save_dialog
        EXPORTING
          with_encoding        = lc_encoding
          initial_directory    = lc_directory
        CHANGING
          filename             = lo_filename
          path                 = lo_path
          fullpath             = lo_fullpath
          user_action          = lo_user_action
          file_encoding        = lo_encoding
        EXCEPTIONS
          cntl_error           = 1
          error_no_gui         = 2
          not_supported_by_gui = 3
          OTHERS               = 4.
      IF sy-subrc <> 0.
        EXIT.
      ENDIF.
    * Check user_action
      IF lo_user_action <> cl_gui_frontend_services=>action_ok.
        EXIT.
      ELSE.
    *   If user_action equals to action_ok, call function module to download datas
    *   using download table i_dwn_tab
        CALL FUNCTION 'GUI_DOWNLOAD'
          EXPORTING
            filename                = lo_fullpath
            filetype                = lc_filetype
            write_field_separator   = lc_separator
            trunc_trailing_blanks   = lc_blank
          TABLES
            data_tab                = i_dwn_tab
          EXCEPTIONS
            file_write_error        = 1
            no_batch                = 2
            gui_refuse_filetransfer = 3
            invalid_type            = 4
            no_authority            = 5
            unknown_error           = 6
            header_not_allowed      = 7
            separator_not_allowed   = 8
            filesize_not_allowed    = 9
            header_too_long         = 10
            dp_error_create         = 11
            dp_error_send           = 12
            dp_error_write          = 13
            unknown_dp_error        = 14
            access_denied           = 15
            dp_out_of_memory        = 16
            disk_full               = 17
            dp_timeout              = 18
            file_not_found          = 19
            dataprovider_exception  = 20
            control_flush_error     = 21
            OTHERS                  = 22.
        IF sy-subrc <> 0.
          MESSAGE i007.
        ENDIF.
      ENDIF.
    ENDFORM.    

  • How could i parse string and link its model with my files in eclipse project?

    How could i parse string and link its model with my files in eclipse project?, as i read that we dont have to use standalone mode while working with eclipse projects.
    Example of what i want to do:
    I have file1.dsl in my project which contains some statements but the declaration of these statements are not in another file, i need to put them only in my code

    Hi Stefan,
    I have eclipse project contains 2 files, file1.dsl and file2.dsl, you can see the contents of the files below.
    file1.dsl contains some statements as shown below and file2.dsl contains the declarations of the variables. (like in C++ or Java we have declarations and usage)
    At this step file1.dsl and file2.dsl will be parsed successfully without any errors.
    Lets imagine that we will delete this project and will create another one and the new project will contain only file1.dsl (which contains the usage)
    At this step this file (file1.dsl) will contains some errors after parsing it, because we are using variables without declarations.
    So what i need is to parse the content of file2.dsl directly without adding this file to the project.
    I need to add the content of file2.dsl directly as a string in the code and parse it. just like that ( "int a;int b;" )
    And link file1.dsl with the model generated after parsing my string
    file1.dsl
    a++;
    b++;
    file2.dsl
    int a;
    int b;
    Thanks

  • How to browse local file using web dynpro

    hi everyone
    How can I browse local file using Web Dynpro?And read file names into Context or array. I have tried the following code but its not working
    String resourcePath = WDURLGenerator.getResourcePath();
    String depObjResourcePath = WDURLGenerator.getResourcePath(“Test”);
    WDDeployableObjectPart appPart = WDDeployableObject.getPart(“Test”, “TestApp”, WDDeployableObjectPart.APPLICATION);
    help required urgently
    Thanks & Regards
    Jaspreet Kaur

    Reply in
    how to browse local file using web dynpro
    Regards,
    Ashwani Kr Sharma

  • Reading a properties file in a servlet and passing its contents to a JSP pa

    Hi all,
    I'm totally new to Servlet pgmg n JSP. Please can ne1 tell how to read a simple properties file (in a servlet) and pass its contents to a JSP page.Actually the reason is to fill a combo box in a JSP page with the contents of a properties file.If calling a servlet for the same is d best way to do that, plz can ne1 tell me :
    1> whether to override the doPost method in the servlet in which to read d file using FileInputStream
    2> Putting the contents in an array and then how to pass this array to the JSP page.
    Thanks,
    deepthy.

    I'm using a properties file to let my web application know what the name of the database is. I'm using an abstract class GeneralDao which will be extended by all the DAO's (Data Access Objects or java classes containing SQL statements).
    Here's the code :
    protected Connection getDatabaseConnection()
              throws Melding
         Connection dbconn = null;     
         ResourceBundle resBundle;
         try
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         resBundle = ResourceBundle.getBundle("gcoConfig");
         String dbConnectie = resBundle.getString("databaseconnection");
         gcoLogger.debug("lezen databaseconnection in resourceBundle " );
         dbconn = DriverManager.getConnection(dbConnectie);
         } catch (InstantiationException exc)The ResourceBundle is used to read the properties file, named gcoConfig.properties.
    With the getString() command I read the content of the string named databaseconnection.
    The gcoConfig.properties file is placed inside the folder C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\gco\WEB-INF\classes
    The GeneralDao is placed in the folder C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\gco\WEB-INF\classes\org\gertcuppens\cluifDao.
    So this class is placed some folder below the WEB-INF\classes folder of gcoConfig.properties.
    And the content of the properties file is just one line :
    databaseconnection=jdbc:mysql://localhost/cluif
    If you want to let the JSP know what's inside the properties file, wrap the content in a Javabean, put it in the request or even the session and pass the control to the JSP.

  • Read a excel file and split its sheets to seperate file ?

    Dear all :
    How to split a excel file into several file, each have one sheet.my code is as below,thanks:
    import org.apache.poi.hssf.usermodel.*;
    import java.io.*;
    import java.util.*;
    import org.apache.poi.poifs.filesystem.*;
    public class Extractxls {
    public static void main(String[] args) throws Exception
    try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    int sheetCount = wb.getNumberOfSheets();
    System.out.println(sheetCount);
    try {
         while(sheetCount > 0) {
         sheetCount--;
         HSSFWorkbook wb1 = new HSSFWorkbook();
         HSSFSheet s = wb1.createSheet();
         String sheetName = wb.getSheetName(sheetCount);
         HSSFSheet sheet = wb.getSheet(sheetName);
    //     HSSFSheet sheet = wb.getSheetAt(sheetCount);
         System.out.println(sheet.toString());
         s = sheet;
    FileOutputStream fileOut = new FileOutputStream("atest" + sheetCount + ".xls");
    wb.write(fileOut);
    fileOut.close();
    } catch (Exception e) {
         System.err.println("Error: " + e.getMessage());
    } catch (Exception e) { e.toString();}

    The HSSFWorkbook class is part of the POI project:
    http://jakarta.apache.org/poi/
    Regards,
    Dave Gilbert
    JFreeChart Project Leader
    I understand poi porject, my problem is that POI can not read a excel file and split its sheets into seperate file (each have one sheet) ?Does any one know how to do it.

  • HT5527 I have had my storage reduced once already.  In the process they removed my "Save" mailbox and all its contents.  I do notcare about contents so much as starting a new Save box.  How?  (OS X 10.7.5)

    My iCloud storage is being reduced.  I have already had it reduced once.  In the process they removed my "Save" mailbox and all its contents.  (One would think that that would be the last thing they removed.  But they took that and the "Trash" mailbox, yet left several thousand old and read messages which were in my "Inbox".)  I do not expect to get the "Save" contents back, but I would like to restore the "Save" mailbox, so that I can start from scratch saving msgs in it again.  But I cannot figure out how to do that.  When I go to "Mailbox" on the top line (between View and Message) and select New Mailbox I get a dialog box in which I can name a new mailbox.  When I type Save, for the name of the new Mailbox I get a response; "The mailbox 'Save" already exists."  But I cannot find it.
    Thanks,  Bill Burner

    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Repair Database. If that doesn't help, then try again, this time using Rebuild Database.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. (In Library Manager it's the FIle -> Rebuild command)
    This will create an entirely new library. It will then copy (or try to) your photos and all the associated metadata and versions to this new Library, and arrange it as close as it can to what you had in the damaged Library. It does this based on information it finds in the iPhoto sharing mechanism - but that means that things not shared won't be there, so no slideshows, books or calendars, for instance - but it should get all your events, albums and keywords, faces and places back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one. 
    Regards
    TD 

Maybe you are looking for

  • Unable to load OSX Tiger after powercut during software update

    My Imac G5 (purchased September 2005), running OSX Tiger, was in the middle of a software update when we had a powercut. Now, when you turn it on, it gets as far as the blue screen with the grey Mac OSX box and status bar (after the grey screen with

  • Best Practices on Mining Industries - CO-PC

    Hello, I am looking for best practices on the mining industry for CO-PC. I am not very familiar with this industry and I don't know if a classic solution based on standard cost price control and material ledger is the most suitable for this business.

  • How to install old version of Flash Player ActiveX

    Hello, I have to install Flash Player ActiveX 10.1.x or 10.3.x because it is required by my application. 11.x version I tried made issues. I downloaded various 10.x versions : they all told me that this version is not the newest => I can only quit th

  • Learn the file size of a PDF or other downloaded file?

    How can I, with my ipad2, learn the size of a PDF file downloaded and libraried in iBooks?  I need the information to decide how I'll distribute it to other users. Thank you.

  • Cannot install BB Desktop Software v7.0 on Windows 7

    I downloaded the new Desktop Software  v7.0 B44, but cannot install it. When I double click on the file (700_b044_multilanguage.exe) it starts extracting itself, and it stops half way (while unzipping Data1.cab) and a message comes up saying "Zip dam