Trying to read a file, and it gives me "java.io.IOException"

I'm writing a little swing text editor for my first java project, and the open method is like this:
public void openFile() throws IOException {
               JFileChooser chooseOpen = new JFileChooser();
               chooseOpen.showOpenDialog(null);
               File openFile = chooseOpen.getSelectedFile();
               FileReader in = new FileReader(openFile);
               BufferedReader br = new BufferedReader(in);
               String fileText = br.readLine();
               output.setText(fileText);
It seems like it should work fine to me, you choose a file, and it opens it, then outputs it to my textArea. I even have it throwing IOException. Why is it giving me that message then? (this is the only method I'm having a problem with.)
the full error message is:
unreported exception java.io.IOException; must be caught og declared to be thrown
openFile();
^
1 error
thanks,
alex

openFile throws an IOException. This is a checked exception which means you must either put it in a try/catch block or throw it in the caller.

Similar Messages

  • Reading a file and changing one part of the file

    I am trying to read a file and then I want to change the first value on each line. The file I am reading is a .HEADER file. Which is just read in notepad I am just opening this like a txt file. I get no say at all how this file is created originally
    I want to change the value on the first line the a new title plus the ext .dat. The file is below. This stays the same format just with different values.
    ECG000 1 171 26112 9:14:56 23/04/2002
    ECG000 8 43(0) 8 127 79 -24066 0 AED trace
    I want to change the ECG000 to a new value eg Pat1.dat on the first line and Pat1 on the second line. When I read this file in and output to the dos window I get ECG000 0 0 0 and that is it. Any ideas why this is happening and how I can replace the values in the file??
         private void FileExt() throws IOException
              System.out.println("In function");
              BufferedReader br = new BufferedReader(new FileReader("c:\\Projects\\FirstSupport\\ECG000.HEADER"));
              String s;
              Vector data = new Vector();
              ECGFile = new FileWriter("c:\\Projects\\FirstSupport\\ECG.txt",true);
              System.out.println("Reading the file");
              while ((s = br.readLine()) != null)
              data.add(s);
              System.out.println(s);
              System.out.println("Finished");
              String label = s.substring(0, s.indexOf(" "));
              System.out.println(label);
              String newLabel = (label+".dat");
              System.out.println(newLabel);
         }

    I think this is what you're looking for:     private void FileExt() {
              java.util.List data=new ArrayList();
              String s;
              try {
                   BufferedReader br=new BufferedReader(new InputStreamReader(
                        new FileInputStream(new File("ECG000.HEADER"))));
                   while ((s = br.readLine()) != null)  {
                        data.add(s);
                        System.out.println(s);
                   br.close();
              catch (FileNotFoundException fnfe) {
                   System.out.println("Input file not found");
                   return;
              catch (IOException ioe) {
                   ioe.printStackTrace();
                   return;
              ListIterator li=data.listIterator();
              try {
                   PrintWriter ECGFile=new PrintWriter(new FileOutputStream(
                        new File("ECG.txt")));
                   while(li.hasNext()) {
                        s=(String)li.next();
                        if (s.substring(0, 6).equals("ECG000")) {
                             s="Pat1.dat"+s.substring(6, s.length());
                        ECGFile.println(s);
                   ECGFile.close();
              catch (FileNotFoundException fnfe1) {}
         }Mark

  • When I open iPhoto 9.2.1 it says that my library needs to be upgraded but when I upgrade the library I am trying to open (33 GB worth of pictures from 2006) the new application says it cannot read the files and how to find them on the system to reimport?!

    When I open iPhoto 9.2.1 it says that my library needs to be upgraded but when I upgrade the library I am trying to open (33 GB worth of pictures from 2006) the new application says it cannot read the files and how to find them on the system to reimport?! and then I'd like to erase the original files since the space requirement is huge!!!! Why is upgrading software iPhoto such a pain. I've gotta get a presentation done and all I get for my money is roadblock!!!

    hello, it sounds like the library is damaged.
    Download iPhoto Library Manager and use its rebuild function. This will create a new library based on data in the albumdata.xml file. Not everything will be brought over - no slideshows, books or calendars, for instance - but it should get all your albums and keywords 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. 

  • I am trying to import cr2files from the camera into lightroom 5 and keep getting an error message saying Lightroom can not read the files and therefore will not import them.  Has anyone had a similar problem-.thanks

    I am trying to import cr2files from the camera into lightroom 5 and keep getting an error message saying Lightroom can not read the files and therefore will not import them.  Has anyone had a similar problem….thanks

    If you are having the same problem, i.e. a disk permission problem, open your favorite search engine and search on, "change disk permissions", and I think you'll find plenty of information on how to fix the problem. This is a Lightroom forum. Your problem is with your operating system. There is no sense in rewriting instructions that are already available if you do a simple search.

  • I tried to download the trial version of elements 10.  I only got the read me files and the organize

    I tried to download the trial version of elements 10.  I only got the read me files and the organizer.

    Please post the PSE query over the following forums and lets discuss it over there.
    http://forums.adobe.com/community/photoshop_elements
    Thanks and regards
    Harshit yadav

  • Reading s file and saving a the dta to an array

    Hi,
    I have a txt file that is contained of text and numbersso this is the format :
    hdfsgfjsgfjsfg
    kshfkwhfl
    kshfakh
    kahflak
    Xunit , YUNIT
    1,2
    2,3
    5,4
    So I want to read this file and save the numbers to two arrays, here is my code, and it gives error on Ch[i] = result[1]; it also say array out of bound and it gives me the watrning that ReadDile.java overrides a depricated API. hELP:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public class ReadFile {
    public static void main(String[] args) throws IOException {
    /*Open the file and Read the file
         File inputFile = new File("wfmdata.txt");
         FileReader in = new FileReader(inputFile); */
         FileInputStream fis = new FileInputStream("wfmdata.txt");
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
         String c;
         String[] T = new String[10012];
         String[] CH = new String[10012];
    int i=0;
    for(;;)
    /*Read one line and store it in variable c */
    c = dis.readLine();
    //if a null line return
    if(c != null)
    if( (c == "XUNIT , YUNIT"))
    continue;
    String[] result = c.toString().split(",");
    T[i] = result[1];
    CH[i] = result [1];
    System.out.println( T[i] + "," + "CH" + result.length);
    i++;
         }else
    dis.close();
    how would I change the code to get rid of the errors!
    there are 10000 lines of numbers(data).
    Sanaz,

    If you are only trying to read in integers i would recommend a different approach. Try using the scanner class. It's new to 1.5 It basically splits up everything in the data source into tokens based on where there is white space. what might interest you is that it has methods to just retrieve primitive types ints, doubles etc.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html
    you might try something like this. It will ignore strings and just handle integers, based on the format you have given.
    import java.util.Scanner;
    import java.io.*;
    public class ReadFile
        public static void readFile() throws FileNotFoundException
            Scanner sc = new Scanner(new FileReader("C:\\YourFile.txt")); // set the source of the data and create a scanner object to tokenize the data
            int[] xUnit = new int[10012]; // initialise the integer arrays
            int[] yUnit = new int[10012];
            while (sc.hasNextInt() == false) // checks to see if the next "token" read by the scanner is an integer
                sc.next(); // moves onto the next token until an int is found.
            for (int count = 0; count < xUnit.length; count ++)  // goes through the array until it hits the end
                xUnit[count] = sc.nextInt(); //assigns the int to the array
                sc.next(); // skips the comma
                yUnit[count] = sc.nextInt(); //assigns the next int to the other array
            for (int count = 0; count < xUnit.length; count ++)
                System.out.println( xUnit[count] + "," + yUnit[count]); //prints out all the data read in
    }Bear in mind my java experience is fairly limited, so this may not be what you're after.

  • ITunes Match has stopped uploading - every file errors and says waiting - I have tried to delete the files and use other formats etc.  I have had the service since Day 1 and NEVER had an issue.  It didn't start until the Delete from Cloud switch to Hide

    iTunes Match has stopped uploading - every file errors and says waiting - I have tried to delete the files and use other formats etc.  I have had the service since Day 1 and NEVER had an issue.  It didn't start until the Delete from Cloud switch to Hide from cloud - the files that do not upload show grayed out on my other devices.

    Have you confirmed that you successfull purged iTunes Match by also looking on an iOS device?  If so, keep in mind that Apple's servers may be experiencing a heavy load right now.  They just added about 19 countries to the service and I've read a few accounts this morning that suggests all's not running perfectly right now.

  • I am trying to open my files and I get the message that the file is invalid.  The index sml file is missing

    I am trying to open my files and get a message saying that the file is invalid.  The index xml file is missong

    Tell us the whole Story in detail about what App (if any), version, any changes you have made recently and Importantly, the exact message - verbatim - a screenshot of the entire display would be very helpful - ÇÇÇ

  • Reading a file and parsing the data for a calculation method

    i am trying to read a file with 3 feilds double double and int . am able to read the file but i am getting an exception right befor i parse the data ...code
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.*;
    //import com.sun.java.util.jar.pack.Package.File;
    public class FileTester {
    public static String mLine;
         public static void main(String[] args) {
              BufferedReader in = null;
              try{
              File f = new File ("loan.txt.txt");
              in = new BufferedReader(new FileReader(f));
              catch(FileNotFoundException e)
                   System.out.println("file does not exist");
                   System.exit(0);
              try{
              String mLine = in.readLine();
              while (mLine != null){
                   System.out.println(mLine);
                   mLine = in.readLine();
              }}catch(Exception e)
              {System.out.println(e.getMessage());
              String []data = mLine.split("\t");
              double loan = Double.parseDouble(data[0]);
              double interest = Double.parseDouble(data[1]);
              int term = Integer.parseInt(data[2]);
              System.out.println(loan+interest+term);
    afterwards i would like to break this up into three methods to feed the values to a calculation class

    Take a look at your while loop. It continues to loop as long as mLine != null. Therefore it stops looping when mLine IS = null. So can you now see why the following line of code would cause problems?
    String []data = mLine.split("\t");How is the data stored in your file? Is it a single line with the three values separated by a tab? If so you can do away with the while loop and just call readLine() once. Otherwise you will have to process each line you read inside the while loop.
    P.S. use the code button when posting code. There is a button above the textfield when use post a reply.

  • Reading a file, and counting how many e's there's in it!

    Hello everyone!
    Well, I'm trying to write a program that'll read a file and count the number of e's in there and print it out.
    This is what the Index.txt file contains:
    In Xanadu did Kubla Khan
    A stately pleasure-dome decree:
    Where Alph, the sacred river, ran
    Through caverns measureless to man
    Down to a sunless sea.And this is my source code:
    import java.io.*;
    public class Appearance{
        public static void main(String[] args) throws IOException{
         index = new BufferedReader(new FileReader(("Index.txt")));
            while((letter = index.readLine()) != null){
       if(letter.contains("e")){
           eCount++;
      System.out.print(eCount + "\n");
      if(index != null){
          index.close();
       index = null;
    private static BufferedReader index = null;
    private static String letter = null;
    private static int eCount = 0;
    }But for some reason when I run it, the output is 4?.. Please tell me why, as I figured that this should work.. :O.

    Vimsie wrote:
    But for some reason when I run it, the output is 4?.. Please tell me why, as I figured that this should work.. :O.Because you are counting the number of lines that contain one or more 'e's. You don't count the occurances.

  • I downloaded ITunes and now I tried to open the file, and it is not supporting the file

    I downloaded ITunes on my galaxy s4 and tried to open the file and it says it is not supported

    Errr, this is a Adobe Lightroom user to user forum, do you have a question about Lightroom?

  • Read a file and maintain a file pointer?

    Hi,
    I need to read a file which has about 1000 records(approx).I need to read 10 records from the beginning of the file and then give the 10 records to a different java process and then continue extracting records for every 10.So how do I save the filepointer and then continue read from the 11th record and then 21st record and so on?
    Remember I don't know the total number of records in the file,but know where exactly I have to extract,I mean the trailer info.
    also, Is there a way to store a file pointer for a particular position in the file and then continue reading the file from the same place by using the saved filepointer?
    any idea?
    also,If I save a filepointer as long value and open the file later using randomaccess file,and seek using this saved long value,will there be any change in the position of the file?will this differ in unix and windows?I mean the file pointer?
    --Robert

    Maybe this will make things clearer. Don't be intimidated, it's not really hardimport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    import java.io.*;
    public class Test extends JFrame {
        static final long RECORD_SIZE = 8;
        RandomAccessFile rf;
        JTextArea jta = new JTextArea();
        JTextField jtf = new JTextField();
        Random r = new Random();
        public Test() {
         try { rf = new RandomAccessFile("rtest.dat", "rw"); }
         catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); System.exit(1); }
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = getContentPane();
         // Set up the GUI
         content.add(new JScrollPane(jta), BorderLayout.CENTER);
         jtf.setPreferredSize(new Dimension(100,20));
         content.add(jtf, BorderLayout.NORTH);
         JPanel buttonPanel = new JPanel();
         content.add(buttonPanel, BorderLayout.SOUTH);
         JButton add10 = new JButton("Add 10");
         buttonPanel.add(add10);
         add10.addActionListener(new ActionListener() {   // Add 10 listener
             public void actionPerformed(ActionEvent ae) {
              try {
                  rf.seek(rf.length());                // seek to end
                  for(int i = 0; i < 10; i++)          // write 10 recs
                       rf.writeDouble(r.nextDouble()*1000000.);
              catch (IOException ioe) { ioe.printStackTrace(); }
              jta.setText("10 records appended");
              showStats();                        // show current statistics
         JButton list10 = new JButton("List Next 10");
         buttonPanel.add(list10);
         list10.addActionListener(new ActionListener() {    // list 10 listener
             public void actionPerformed(ActionEvent ae) {
              jta.setText(null);
              try {
                  for(int i = 0; i < 10; i++) {
                   if (rf.getFilePointer()<rf.length()) {  // if not eof
                       long recNo = rf.getFilePointer()/RECORD_SIZE;
                       jta.append(""+recNo+") "+Double.toString(rf.readDouble())+"\n");
                   } else jta.append("(eof)\n");
              } catch (IOException ioe) { ioe.printStackTrace(); }
              showStats();                        // show current location/size
         JButton random10 = new JButton("List Random 10");
         buttonPanel.add(random10);
         random10.addActionListener(new ActionListener() {   // list 10 random records
             public void actionPerformed(ActionEvent ae) {
              jta.setText(null);
              try {
                  for(int i = 0; i < 10; i++) {
                   // Get a rendom record number
                   int recNo = r.nextInt((int)(rf.getFilePointer()/RECORD_SIZE));
                   // seek to it
                   rf.seek(recNo*RECORD_SIZE);
                   // read record, add to textarea
                   jta.append(""+recNo+") "+Double.toString(rf.readDouble())+"\n");
              } catch (IOException ioe) { ioe.printStackTrace(); }
              showStats();
         buttonPanel.add(random10);
         JButton rewind = new JButton("Rewind");
         buttonPanel.add(rewind);
         rewind.addActionListener(new ActionListener() {  // rewind listener
             public void actionPerformed(ActionEvent ae) {
              jta.setText(null);
              try {
                  rf.seek(0);                     // move to beginning
              } catch (IOException ioe) { ioe.printStackTrace(); }
              jta.setText("Rewound");
              showStats();                    // show size/location
         buttonPanel.add(rewind);
         showStats();
         setSize(600,500);
         show();
        private void showStats() {
         try {
             jtf.setText("Cnt="+(rf.length()/RECORD_SIZE)+
                   ", Cur="+(rf.getFilePointer()/RECORD_SIZE));
         } catch (IOException ioe) { ioe.printStackTrace(); }
        public static void main(String[] args) { new Test(); }
    }

  • Program to read html file and to open the links in that html file

    program to read html file and to open the links in that html file..
    ex:- to read automatically all next links in the html file and save it hard disk

    Start here;
    http://java.sun.com/products/jfc/tsc/articles/bookmarks/
    It gives you all of the information you need to parse the HTML file using the HTMLEditorKit that is a part of the Java SDK.
    Once you get the links from the file, then you can think about connecting to each.

  • How to read flat file and convert to xml throught OSB

    Hi ,
    Can somebody help how to read flat file and convert to xml in OSB.
    appreciate ur help.
    Thanks & Regards ,
    Siva K Divi

    if you're using the oepe with osb plugin (will be installed when you install the osb locally) and then in your osb project > rightmouseclick > new > MFL.
    that's it
    maybe you're trying to create it within an oepe installation which doesnt have the osb plugin ?

  • Every time I sign in, it signs me out immediately. I've tried deleting the opm file and it's unable to do so because "Adobe CC is currently running this file." I've also changed my LAN settings and downloaded something else that was supposed to help me ou

    Every time I sign in, it signs me out immediately. I've tried deleting the opm file and it's unable to do so because "Adobe CC is currently running this file." I've also changed my LAN settings and downloaded something else that was supposed to help me out but nothing seems to fix the problem.

    I think you'll find that the official Adobe advice here is misguided.  First, deleting bits of the program and program data is, as you've noted, perilous and often impossible.  Shame on Adobe for doing such a poor job of coding that such steps are needed.
    The solution I recommend is as follows:
    Restart your Windows machine and boot in "Safe Mode" with networking using the F8 key just as Windows starts.
    Go to the Control Panel and select Programs. Find and Uninstall "Adobe Creative Cloud Desktop". 
    Reinstall it by downloading it from the website  https://creative.adobe.com/products/creative-cloud
    Restart your machine.
    Only in "Safe Mode" are you likely to be able to accomplish these tasks reliably.

Maybe you are looking for

  • E-mail motivos de rejeição NFe 10.0

    Boa tarde. Estamos realizando a implemnetação da solução NFe 10.0 , entrada automática. Estou com o seguinte problema para o envio de notificação em caso de rejeição da NFe. Configurei os motivos de rejeições no PI . Configurei as mensagens na SO10 p

  • Posting the MIRO Document with reference of PO

    Hello friends while user posting the MIRO Document with reference of PO , he is getting difference in balance Total amount is 31,237.00 Posting amount is 28,320.05 Balance amount is 2,916.95 this balance amount not getting post in MIRO Before that i

  • DVD drive doesn't recognize blank DVDs or allow burns

    I got a 20", 2.4 Ghz Intel Imac not too long ago, with Leopard already installed. I'd been using Parallels or Boot Camp to do all by DVD burning in Windows until recently. The first time I tried to do it in OSX 10.5.1, it didn't work right. The DVD i

  • Soa11g: DB Adapter Delete Operation and Transaction

    Guys, I need your help to understand the transaction flow in SOA 11g. We have two table with primary and foreign key replationship. Master Table: Employee (empId Primary Key) Child Table : Department (empId Foreign Key) Employee is associated with De

  • Why did Apple drop support on Windows XP 64-bit, but not on 32-bit?

    I have Windows XP 64-bit and do not feel the need to get a new computer or upgrade the operating system.  What I wonder is why Apple still makes iTunes for 32-bit XP and not 64-bit XP?