FileReader

I was wodnering if anyone could tell me where I need to place the file that I would like the java code to read. I've tried various places and they allcome up with File not Found errors. Thanks for any help you can offer

hmm. here is the section the program seems to pay no attention to and therefore wont read the file:
  static int count = 0;
     // Declares Values in the array
     static String [] anArray = new String[count];
       public void readFile() throws IOException{
        try{   // Open new file
           File inFile = new File("brit-a-z.txt");
           // Create a file stream, wrapping the file
           FileReader fileReader = new FileReader(inFile);
           // Create a second wrapper,
           BufferedReader bufReader = new BufferedReader(fileReader);
           // Read in the first line...
           String s;
           //Tries to read forever
           while (true) {
              s = bufReader.readLine();
             anArray[count] = s;
              count++;
               // a null reference is returned if the end of file
               if(s==null) throw new EOFException("Hello");
              System.out.println("found"+s);
        catch (FileNotFoundException e) {
            System.out.println("Warning, FileNotFound exception raised"+e);
        catch (IOException e) {
            System.out.println("Warning, I/O exception"+e);
}

Similar Messages

  • FileReader and StringTokenizer

    what I'm trying to do is to read String and Double date in a txt document here my code:
    import java.io.*;
    import java.util.*;
    public class partie1 {
         static final int limite_colones=10;
         static final int limite_lignes=10;
         static final int limite_matieres=5;
         static final int limite_eleves=15;
         static final String titre="�cole secondaire Cartierville";
         static String nomEleve[]=new String[limite_eleves];
         static double notesEleve[][]=new double[limite_eleves][limite_matieres];
         public static void main(String[] args)throws IOException {
              String ligne,ficEleve="c:/ficEleves.txt";
              BufferedReader ficnomlogique=new BufferedReader(new FileReader(new File(ficEleve)));
              while ((ligne=ficnomlogique.readLine())!=null){
                   StringTokenizer ligneTemp=new StringTokenizer (ligne,":");
                   for(int i=0;i<15;i++){
                        nomEleve=ligneTemp.nextToken();
                        System.out.println(nomEleve[i]);
                        for(int j=0;j<5;j++){
                             notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
                             System.out.println(notesEleve[i][j]);
    and this is what they give me as error message:
    Alain
    100.0
    90.0
    88.0
    60.0
    65.0
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknow Source)
    at partiel.main(partie1.java:20)
    so i understand that it doesnt change ligne or doesnt do the for correctly but i can't figure where is my mistake.
    thank for your help

    What do the records in the file look like?
    This code:
    for(int i=0;i<15;i++){
        nomEleve=ligneTemp.nextToken();
    System.out.println(nomEleve[i]);
    for(int j=0;j<5;j++){
    notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
    System.out.println(notesEleve[i][j]);
    will call nextToken() on each line 15 + (15 * 5) = 90 times.
    Does each line contain 90 tokens?

  • How to get the number of lines of a FileReader

    I need to calculate the number of lines of a FileReader object. How can I do that ?

    I wrote the following some while ago. It assumes that a line is terminated by '\n' but it should be easy to adapt.
    import java.io.*;
    public class LineCounter
        public static int countLines(File file, String encoding) throws IOException
            int lineCount = 0;
            Reader reader = new InputStreamReader(new FileInputStream(file), encoding);
            char[] buffer = new char[4096];
            for (int charsRead = 0; (charsRead = reader.read(buffer)) >= 0;)
                for (int charIndex = 0; charIndex < charsRead ; charIndex++)
                    if (buffer[charIndex] == '\n')
                        lineCount++;
            reader.close();
            return lineCount;
        public static void main(String[] args)
            try
                File file = new File("/home/sabre/work/dev/maps/EUROPE.RIV");
                long startTime = System.currentTimeMillis();
                int lineCount = countLines(file, "UTF-8");
                double time =  (System.currentTimeMillis() - startTime) / 1000.0;
                System.out.println("File size = " + file.length() + " contains " + lineCount + " lines taking " + time);
            catch (Exception e)
                e.printStackTrace();
    }

  • Reading file in bytes using FileReader...

    Hi,
    I am trying to read out bytes value from a .bmp file then i try to change the byte values that i read out to hexadecimal value.
    I open the .bmp in Win Hex (a software) but the hexadecimal value does not tally....
    public void readByteFile (String path)
    Vector in = new Vector ();
    try
    FileReader reader = new FileReader (path);
    int c;
    while ((c = reader.read ()) != -1)
    String hex = Integer.toHexString (c);
    reader.close ();
    } catch (FileNotFoundException e) {System.err.println(e);}
    catch (IOException e) {System.err.println(e);}
              return in;
         }

    If you want to read the actual bytes from the file then do not use a Reader. That will convert the bytes to characters as if they were text. Use an InputStream instead.

  • Accessing a file through FileReader

    I've to give the full path while accessing the file using the following code. Is there any alternative where i can provide the relative path and still get the desired result?
    BufferedReader in = new BufferedReader (new FileReader ("/apps/secDBadmin/classes/database.cfg"));
    I'm accessing the file database.cfg from a class which is inside the same folder (/apps/secDBadmin/classes).

    Did you try ClassLoader.getResourceAsStream(String)
    For your case the code will look something like,
    Class c = Class.forName(YouClassName);
    or
    Class c = this.getClass();
    InputStream in = c.getClassLoader().getResourceAsStream("JustTheFileName");
    BufferedReader rd = new BufferedReader(new InputStreamReader(in));

  • FileReader + ftp path of the file

    Hello everybody.
    I am trying to open a file using the FileReader but unfortunatelly the file is on an FTP server.
    My problem is that when I pass the path of the file e.g.
    ftp://pavlos/zzz.txt
    as a parameter to the FileReader
    it changes it automatically to: ftp:\pavlos\zzz.txt
    and obviously it can not access it.
    Could anybody suggest something?
    Thanks a lot

    A FileReader is just to read from files, local or over a network drive, but not using another protocol like ftp.
    What you might want is to use a UrlConnection. See java.net.URL.openConection() and java.net.URLConnection.getInputStream(). You may then wrap a java.io.InputStreamReader to get a Reader interface, if required.

  • Filereader only reads when launched from terminal

    My program consists of a JDialog which is launched from a JApplet. Part of my code requires that an input string be checked against a "dictionary" to see if it is a valid word. The dictionary consists of several word lists, organized by length, in a folder called "Data."
    Here is the relevant code:
         public boolean checkDictionary (String word) {
              boolean acceptable = false;
              try {
                   BufferedReader reader = new BufferedReader(new FileReader("Data/"+word.length()+"lw.txt"));
                   String stringRead = reader.readLine();
                   while(stringRead != null) {
                        stringRead = reader.readLine();  // read next line
                        if (stringRead.equals(word)) {
                             acceptable = true;
                             reader.close();
                   reader.close();
              catch (Exception ex) {
              return acceptable;
         } When I run the program from the terminal (either by typing "java Anagrams" or "firefox Launcher.html"), everything works fine, but if I run it by double-clicking the Launcher.html icon, it fails to read the data files. Everything else in the program works normally, and it doesn't make any difference whether I use a web browser, or appletviewer. Unfortunately, I can't tell what exception is thrown, because the output isn't sent to a terminal.
    Any ideas?

    It doesn't answer you question but the logic of that method is incorrect: it never checks the first String in the file and it always reads all the words no matter whether or not the word was found already. Make that:
         public boolean checkDictionary (String word) {
              boolean acceptable = false;
              try {
                   BufferedReader reader = new BufferedReader(new FileReader("Data/"+word.length()+"lw.txt"));
                   String stringRead = reader.readLine();
                   for (String stringRead= reader.readLine(); stringRead != null; stringRead= reader.readLine()) {
                        if (stringRead.equals(word)) {
                             acceptable = true;
                             break;
                     reader.close();
                catch (Exception ex) {
              return acceptable;
         } kind regards,
    Jos

  • Transforming a String in a FileReader

    Dear Srs,
    I'm developing an ASP page that write a text file to server. In the next page I developed an applet that read this file and calls a class to process it. I read the text file and I have a String as file content. But the class wait for a FileReader parameter and I can't modify the class to receive a String. As not is possible to write this String in a file in the client, read it and pass to my class, I aks for you: How can I convert my String in a FileReader? If not, what is the other manner to pass the string for my class?
    Thanks a lot,
    Vinicius Machado

    A FileReader needs to read from a file. You can't create a file, so you cannot use the method that requires a FileReader. Is there no other method that just uses a Reader, or something general like that? That would have been a good design. Requiring a specific input source is a bad design. If you have the ability to change this class, I suggest you do so. If you don't, you appear to be out of luck until you find something better.

  • Orderbooking: FileRead Adapter problem

    Hi,
    Im currently having problems getting through the tutorial chapter 8. Im trying to implement the File Adapter functionality to read the xml files. Everything goed OK with compiling and deploying. But when i open the dashboard and try to check out the process it gives this error:
    Error Message:
    Cannot find partnerLinkType 2. PartnerLinkType "{http://xmlns.oracle.com/pcbpel/adapter/file/FileRead/}Read_plt" is not found in WSDL at "http://WP200011-001:9700/orabpel/default/BatchOrderProcessing/1.0/_BatchOrderProcessing.wsdl". Please make sure the partnerLinkType is defined in the WSDL.
    I tried to rebuild the workflow several times watching if i have forgotten something but it wasnt. I tried to use logical directories instead of Physical but none of those solutions worked.
    Note is that i run my BPEL server on an external machine cuase its very resource demanding. The physical directories are of course also available on the server. My workstation is running XP and the deploy server windows 2000.
    Does anyone knows how to solve this? thnx

    Welcome to Apple Discussions!
    It sounds like you may have a faulty DC IN Board. One end of the DC In Board is where you plug in your power adaptor, and your description of your problem sounds like this is where the damage is. Replacing the DC In board is not too bad to do. To see what it looks like and what is involved, go to:
    http://www.ifixit.com
    Look up your exact iBook and the DC In Board and you will find a picture of the the DC In Board and a detailed description of how to replace it. You could do the work yourself or have it done by a qualified repair shop. You may also need a new power adaptor--it could also be damaged from your description, but I'm not sure about that. Sparks are not a good sign.
    Good luck!

  • Help with filereader

    i am looking for some filereader code and have not been located it by searching google if someone could give me an example code or point to a good tutorial besides the one on Sun's webpage that would be great
    i have important the correct class and have the reader and the buffer line i just need the part of the code that it reads.
    Is there a way to have it keep on reading different lines intill it there is no more lines to read?
    Message was edited by:
    Wrestler77

    maybe this will help you: http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html

  • FileReader (?) problem

    I'm not sure wether this is a problem with the FileReader or Internet Explorer but as other applications seem to have no problems I tend to think its Java.
    Anyway, I'm trying to read in a web page, that was saved from the browser, as a String in Java. To do this I'm using the 'FileReader' class but it seems the FileReader has some problems with webpages saved from IE (no problems with Firefox pages though).
    Using this code:
    try {
         char[] buffer = new char[1024];
         FileReader r = new FileReader(new File("form_ie.html"));
         String result = "";
         while(true) {
              int num = r.read(buffer);
              if(num <= 0) break;
              result += new String(buffer,0,num);
         System.out.println(result);
    catch(Exception ex) {
         ex.printStackTrace();
    }The result is two strange characters at the start and then every two characters has value (as byte) of 0. Opening this site in notepad/firefox/ie/... gives no problems. Any idea what causes this and what can I do about it? (I'm currently removing char's with a byte value <=0)
    The webpage I'm testing can be found on: http://student.kuleuven.be/~s0109731/Rommel/ under the filename "form_ie.html". This webpage was generated using Javascript so there might be no problems for regular webpages.
    Now after reading in this webpage, I extract the internal xml block. This xml block is send to a SAXParser but as this SAXParser only accepts InputStreams, I need to turn a String into an InputStream. I found the java.io.StringBufferInputStream class but its deprecated and I can't find an alternative to turn a String into an InputStream. Any suggestions?

    It's not generally possible to detect the encoding, no. Some specific patterns (like the byte order marks) might hint at an encoding (in this case UTF-16 - I really didn't mean UTF-8 earlier!), but they would also be perfectly valid characters if the stream were ISO-8859-1 encoded.
    XML documents tell you there encoding (in the ?xml processing instruction) - of course, parsers have to do a bit of work to figure out what the byte encoding is before they can read the characters, but given that they're looking for specific patterns, that's pretty straightforward.
    HTML documents generally don't self-identify. XHTML documents can (because they're XML). So, for HTML, the web-server normally tells you the character encoding in an HTTP header. But of course, you've already lost this information.
    The reasons this is working if saved in FireFox and not IE, is that I expect IE is just saving out what it received whereas FireFox will be translating to your platform's default encoding where possible.
    As to your other question, StringBufferInputStream is indeed deprecated in favour of StringReader. But as you said, XML parsers need byte streams, not readers full of characters (because they want to do their own decoding according to the XML PI).
    Sun's silly forum software only lets you see the message you are replying to, not the whole thread, so I don't know what you were originally after, but notice that SAXParser also has parse() methods that take Files and InputSources. These may help. Note that an InputSource can be constructed from a Reader (but it mustn't contain a BOM which we've already decided you have).
    Also, why read the file into a String? Why not read it into a byte array? This would be the preferred way of dealing with XML. Then you could make a ByteArrayInputStream from the byte[], and wrap that in an InputSource and you aren't mucking with any character encoding stuff outside of the XML.

  • FileReader - Unreported exception

    Me again!!
    Having problems with FileReader - here's my code:
    void button1_actionPerformed(ActionEvent e)
        FileReader file = new FileReader ("d:\\a.txt");
        BufferedReader inputFile = new BufferedReader(file);
        String input = inputFile.readLine();
        textField1.setText(input);
      }Getting two unreported exception errors - how can I get rid of those?
    NB. java.io.*; is imported...
    Please help!!
    Thanks,
    Sam

    If you look at the API docs, you'll see that many methods throw exceptions. Normally you'll want to use try/catch blocks to deal with exceptions when they occur.
    If you look at the constructor for FileReader, you'll see that is throws a FileNotFoundException. If you look at the readLine() method of class BufferedReader you'll see that it throws an IOException. As FileNotFound is a subclass of IO then you can deal with them both in the same catch block:
    try
        FileReader file = new FileReader ("d:\\a.txt");
        BufferedReader inputFile = new BufferedReader(file);
        String input = inputFile.readLine();
        textField1.setText(input);
    catch(IOException ioex)
        System.out.println(ioex.toString());
    }

  • FileReader Seeing Double

    I am using the following code to read a text file. When it reads a file, it outputs the file plus the first half of the file attached to the end. So when I try to read any given file, I reveive a file and a half back. Help?!?
    FileReader in = new FileReader(xslFile);
    StringBuffer outBuf = new StringBuffer();
    char[] buf = new char[8192]; // 8 K
    int read = -1;
    while((read = in.read(buf)) != -1){
    outBuf.append(buf);
    xslContents = outBuf.toString();

    Ah, I think I've got it. Thanks for your help!
    FileReader in = new FileReader(xslFile);
    StringBuffer outBuf = new StringBuffer();
    char[] buf = new char[8192]; // 8 K
    int read = -1;
    while((read = in.read(buf)) != -1){
    outBuf.append(buf, 0, read);
    xslContents = outBuf.toString();
    in.close();

  • Filereader at OSX platform

    Hello
    i use a filereader to read from a txt file.
    running the programm with OS X all special characters are not shown correct.
    i have searched some time to find a solution, but i can't find it.
    the filereader uses the default encoding, so i can't set no charset.
    maybe the filereader has no UTF-16 support at OSX platform ?
    please help
    String inputline = "";
    FileReader txtfile = new FileReader(file);
    in = new BufferedReader(txtfile);
    while ((inputLine = in.readLine()) != null)
    // do something

    FileReader uses the system's default encoding, which most likely is not UTF-16. It's probably ISO-8859-1 or UTF-8 or some Macintosh-specific encoding.
    To use a different character encoding you need to go a little longer route and use InputStreamReader with FileInputStream, like suggested in the API documentation of FileReader: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileReader.html InputStream fileStream = new FileInputStream(yourFileHere);
    Reader txtfile = new InputStreamReader(fileStream, "UTF-16");
    in = new BufferedReader(txtfile);
    while ((inputLine = in.readLine()) != null)
        ...

  • 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....

Maybe you are looking for

  • How to build a site map in Release 2 portal

    Can any one tell how to generate a site map in portal release 2. We have all portal pages stored in pages group. Thanks.

  • Event triggering changes back to consumer class

    Hi all, newbie at Java and I hope you can give me a hand on this. Suppose I have 2 classes A and B. A has an instance of B, an event takes place in B and is caught by a listener in B. Can the listener call a method in A? I cant see how this can be do

  • Continuously have to restart apple tv

    I'm having issues with apple tv intermittently working and constantly rebuffing. This is happening when I'm streaming, air play, and using home share, pretty much every option is giving me problems. To fix the issue I have to restart apple tv then it

  • Best way to wipe iPhone 3G?

    Just upgraded to an iPhone 4 and will pass my iPhone 3G onto a new owner - but first want to wipe all the data - how is this best accomplished? Oh and incase anyone is interested - the iPhone 3G was purchased in Belgium and is thus unlocked as Belgiu

  • HT4221 how to delete a photo album

    I need to delete a photo album from Apple ipod 4th generation 8gb.