Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    manou2324 is offline Member
    Join Date
    Mar 2013
    Posts
    56
    Rep Power
    0

    Default read a file caracter by caracter

    hi,

    i need to read a text file caracter by caracter.
    i tried :

    Java Code:
     try
             {
       	lecteurAvecBuffer = new BufferedReader(new FileReader("D:\\fichier.txt"));
             }
           catch(FileNotFoundException exc)
             {
       	System.out.println("Erreur d'ouverture");
             }
         while ((ligne = lecteurAvecBuffer.readLine()) != null)
           {
    
       //i want to read "ligne" caracter by caracter because i will test everyone of these carateres
    }
    please what can replace this comment?

    thank you

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,097
    Rep Power
    20

    Default Re: read a file caracter by caracter

    First off, move the while loop inside the try block.
    No point reading the file if you've already had a FileNotFound thrown.

    Second, the API is your friend.
    toCharArray.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    393
    Rep Power
    5

    Default Re: read a file caracter by caracter

    You can use the toCharArray() method of the String class.

    EDIT: Just beaten to it.

    Regards.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    Did you read the BufferedReader API? BufferedReader (Java Platform SE 7 ) The method to read a character is clearly documented.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    manou2324 is offline Member
    Join Date
    Mar 2013
    Posts
    56
    Rep Power
    0

    Default Re: read a file caracter by caracter

    i wrote this:
    [CODE]
    while ((ligne = lecteurAvecBuffer.readLine()) != null)
    {
    while (c=ligne.read()!=-1)
    System.out.println(c); }
    [\CODE]
    but the method read is undefined for the type string..
    i declared "ligne" as a string variable..how can i solve this point?

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    You stated you wanted to read in a character at a time. Here is an example.

    Java Code:
    String inputFile = "your input file here";
    try {
          BufferedReader reader = new BufferedReader(new FileReader(inputFile));
          char c;
          while ((c = (char)reader.read()) >= 0) {
              System.out.print(c);
          }
          reader.close();
    } catch (IOException ioe) {
           ioe.printStackTrace();
    }
    Or you can do as explained earlier by reading in a line and then converting the line to a character array.

    Note: I made a mistake in this. However, I fixed it in a later post and am leaving this as is (otherwise follow-on posts won't make sense). Change char c to int c and cast the c to char in the print statement.

    Regards,
    Jim
    Last edited by jim829; 04-13-2013 at 08:53 PM. Reason: Point out error
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    manou2324 is offline Member
    Join Date
    Mar 2013
    Posts
    56
    Rep Power
    0

    Default Re: read a file caracter by caracter

    I tried this code but it dispalys an infinity og question marks :

    Java Code:
    String inputFile = "your input file here";
    try {
          BufferedReader reader = new BufferedReader(new FileReader(inputFile));
          char c;
          while ((c = (char)reader.read()) >= 0) {
              System.out.print(c);
          }
          reader.close();
    } catch (IOException ioe) {
           ioe.printStackTrace();
    }

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    That was just an example of how to read a character at a time. Printing out the characters may be inappropriate based on the content type. Are you reading a text file? What happens when you just read a line at a time using readLine and print that out?

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    manou2324 is offline Member
    Join Date
    Mar 2013
    Posts
    56
    Rep Power
    0

    Default Re: read a file caracter by caracter

    this code
    Java Code:
    try
             {
        lecteurAvecBuffer = new BufferedReader(new FileReader("D:\\fichier.txt"));
             }
           catch(FileNotFoundException exc)
             {
        System.out.println("Erreur d'ouverture");
             }
         while ((ligne = lecteurAvecBuffer.readLine()) != null)
           {
     
       //i want to read "ligne" caracter by caracter because i will test everyone of these carateres
    }
    displays every line like it is,that means it prints what is written in the file

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    I'm sorry, I made a mistake (I really hate it when I do that). My file printed out correctly and I never saw any odd characters. But the loop didn't terminate either. Please try this.

    Java Code:
    String inputFile = "your input file here";
    try {
          BufferedReader reader = new BufferedReader(new FileReader(inputFile));
          int c;
          while ((c = (char)reader.read()) >= 0) {
              System.out.print((char)c);
          }
          reader.close();
    } catch (IOException ioe) {
           ioe.printStackTrace();
    }
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    manou2324 is offline Member
    Join Date
    Mar 2013
    Posts
    56
    Rep Power
    0

    Default Re: read a file caracter by caracter

    I did a copy+paste of this code,i changed the print by a println but it still displays this :

    ?
    ?
    ?
    ?
    ?
    ?
    ?
    ?

    i can't see where is the problem

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    And I assume you added your file name. Otherwise, I don't know. The above worked just fine for me.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    manou2324 is offline Member
    Join Date
    Mar 2013
    Posts
    56
    Rep Power
    0

    Default Re: read a file caracter by caracter

    sure i did

  14. #14
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    Okay, perhaps there is something unique about your text file. I have attached a very simple one. See if you can read that one with the latest version of the code segment I sent.

    Regards,
    Jim
    Attached Files Attached Files
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  15. #15
    manou2324 is offline Member
    Join Date
    Mar 2013
    Posts
    56
    Rep Power
    0

    Default Re: read a file caracter by caracter

    I tried with your file but there is the same problem.
    As a good solution,i found this code :

    Java Code:
    public static java.util.ArrayList retourneLignes(String chemin) throws Exception {
        java.util.ArrayList retour = new java.util.ArrayList();
        java.io.FileReader reader = null;
        try {
          reader = new java.io.FileReader(chemin);
          int i = 0;
         
          while (i != -1) {
            i = reader.read();
            char c = (char) i;
           System.out.println(c);
          }
        }
        catch (IOException ex) {
          reader=null;
          throw new Exception("Erreur dans la lecture du fichier \""+chemin+"\".");
        }
        reader=null;
        return retour;
      }
    and it works well

    Thank you

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    Okay. I can't explain it because I read my text file just fine using the code. But I'm glad you found a working solution.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  17. #17
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: read a file caracter by caracter

    Java Code:
    int c;
    while ((c = (char)reader.read()) >= 0) {
    This code looks odd. c is declared as an int, but the cast to char means it will be assigned a value in the range '\u0000' to '\uffff'. That is, it will never be negative.

    @OP: do use a BufferedReader. And if you'll be checking every character, tolls' and Ronin's suggestion of using toCharArray() gets my vote.

  18. #18
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    It's odd alright! And the problem is that I edited an earlier post to correct my mistake but forgot to take out the cast. And adding insult to injury the toCharArray() method is more efficient. I really hate cluttering up this forum with bad advice and wasting the poor OP's time.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  19. #19
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: read a file caracter by caracter

    Well two people had mention toCharArray(), so it's really up to the OP to ask if that wasn't clear.

    Your question (now deleted) was a reasonable one. (Along the lines of "is toCharArray() really more efficient?") Personally I don't know anything about the internals of the standard Java classes. (I don't despise those who do - but I'm just not one of their number.) I tend to go by the documented methods and the prejudice that classes expose methods for some good reason - like efficiency or whatever. BufferedReader has a method for reading lines, so I figure whatever its buffering process is, it will be good at returning whole lines of text. And String has a toCharArray() that - I suppose! - the Java runtime writers have highly optimized to produce a copy of whatever array the String is using internally.

    So, for me, toCharArray() is just a kneejerk. It depends on what the OP is doing of course (eg he or she could be reading a Gb of text without any \n in it, but also depending on the checks that are being done having a whole array could be really handy for an occasional "backward glance")

  20. #20
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: read a file caracter by caracter

    Out of curiosity I did some testing of my own. The toCharArray of String and using readLine was about twice as efficient as using the single character read method of the BufferedReader. The file was 5Mbytes and the toCharArray test also included iterating through the new array and assigning to a char. However, the read(char [] cbuf, int off, int len) method of BufferedReader using an array size of 8000 was significantly more efficient than the latter two. About 2.5 times as fast as the toCharArray() method and also iterating through the array and assigning to a char. The same 5Mbyte file was used.

    I usually try to judge efficiency by looking at the API and also the code. I figure the designers wouldn't have gone to the trouble to put certain methods in there if they weren't more efficient. This time, however, I was wrong. Or I used it for other than it was intended.

    Regards,
    Jim
    Last edited by jim829; 04-14-2013 at 08:06 AM. Reason: spelling
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 8
    Last Post: 07-25-2012, 11:00 AM
  2. Replies: 1
    Last Post: 08-05-2011, 10:21 PM
  3. Replies: 2
    Last Post: 05-11-2009, 11:07 AM
  4. Replies: 0
    Last Post: 02-11-2009, 10:53 AM
  5. Replies: 5
    Last Post: 02-05-2009, 11:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •