Scanning characters in a text file

Hello, firstly I am trying to get the program to work, then I will use different methods (program description shown in code).
I have not done Java for a while therefore I do not know if i am on the right track or not - please say. Basicly I have the characters in an array, but when I display them its looks like 160, 160, 12, 13, etc etc i.e. their is a separate number for each character.
What I need to know is how to I get this number back to a character?
Thank you anyone
import java.io.*;
* Write an application which scans through a text file, and counts
* (and displays) the occurrences of a particular character (supplied
* by the user) on each line of the file. Use a method to count the
* occurrences on one line. The specification of the method should be:
* private int countCharacters(String line, char c)
* The method returns the number of �c� character in the line.
public class TextfileScan2
     public static void main(String[] args)throws Exception
          byte[] byteArray = new byte[100];
          FileInputStream in = new FileInputStream("File.txt");
          int byteRead;
          int index = 0;
          while ((byteRead = in.read()) != -1)
               byteArray[index] = (byte)byteRead;
               index++;
          in.close();
          for(int i = 0; i < byteArray.length; i++)
               System.out.println(byteArray);

No need to get quite so uptight. Anyway I think I am making progress although what I have does not compile as it says I need to add curly braces to lines 28 and 44.
Can someone please tell me why I get this error. Maybe the name of the methods - have tried changing but no luck.
cheers
import java.io.*;
* Write an application which scans through a text file, and counts
* (and displays) the occurrences of a particular character (supplied
* by the user) on each line of the file. Use a method to count the
* occurrences on one line. The specification of the method should be:
* private int countCharacters(String line, char c)
* The method returns the number of �c� characters in the line.
public class TextfileScan2
     public int main(String[] args)throws Exception
          BufferedReader in = new BufferedReader(new FileReader("File.txt"));
          String line = null;
          String lines = null;
          while((line = in.readLine()) != null)
               lines = line;
          countCharacters(line);
     private int countCharacters(String line)
          char[] charArray = line.toCharArray();
          int c = 0;
          for(int i = 0; i < charArray.length; i++)
               if(charArray[i] == 'c')
                    c++;
          System.out.print("There are " + c + " 'c' characters in line");
}

Similar Messages

  • Reading characters from a text file into a multidimensional array?

    I have an array, maze[][] that is to be filled with characters from a text file. I've got most of the program worked out (i think) but can't test it because I am reading my file incorrectly. However, I'm running into major headaches with this part of the program.
    The text file looks like this: (It is meant to be a maze, 19 is the size of the maze(assumed to be square). is free space, # is block, s is start, x is finish)
    This didn't paste evenly, but thats not a big deal. Just giving an idea.
    19
    5..................
    And my constructor looks like follows, I've tried zillions of things with the input.hasNext() and hasNextLine() to no avail.
    Code:
    //Scanner to read file
    Scanner input = null;
    try{
    input = new Scanner(fileName);
    }catch(RuntimeException e) {
    System.err.println("Couldn't find the file");
    System.exit(0);
    //Set the size of the maze
    while(input.hasNextInt())
    size = input.nextInt();
    //Set Limits on coordinates
    Coordinates.setLimits(size);
    //Set the maze[][] array equal to this size
    maze = new char[size][size];
    //Fill the Array with maze values
    for(int i = 0; i < maze.length; i++)
    for(int x = 0; x < maze.length; x++)
    if(input.hasNextLine())
    String insert = input.nextLine();
    maze[i][x] = insert.charAt(x);
    Any advice would be loved =D

    Code-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
    ******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
        for(int x = 0; x < maze.length; x++) {
            if (input.hasNextLine()) {
                String insert = input.nextLine();
                maze[x] = insert.charAt(x);
    }Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
        if (input.hasNextLine()) {
            String insert = input.nextLine();
            for(int x = 0; x < insert.size(); x++) {
                maze[i][x] = insert.charAt(x);
    }Otherwise, only one character per line is read and storing a character actually should fail.

  • Non printable characters in a text file..

    hi,
    How to get blank lines and non-printable characters
    and remove those characters from the text file being uploaded from application server .
    thanks,
    Anil.

    Take a look at the constants in cl_abap_char_utilities. A simpler solution would be to ask for a file without such characters...

  • Removing the Control Characters from a text file

    Hi,
    I am using the java.util.regex.* package to removing the control characters from a text file. I got below programming from the java.sun site.
    I am able to successfully compile the file and the when I try to run the file I got the error as
    ------------------------------------------------------------------------D:\Debi\datamigration>java Control
    Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repet
    ition
    {cntrl}
    at java.util.regex.Pattern.error(Pattern.java:1472)
    at java.util.regex.Pattern.closure(Pattern.java:2473)
    at java.util.regex.Pattern.sequence(Pattern.java:1597)
    at java.util.regex.Pattern.expr(Pattern.java:1489)
    at java.util.regex.Pattern.compile(Pattern.java:1257)
    at java.util.regex.Pattern.<init>(Pattern.java:1013)
    at java.util.regex.Pattern.compile(Pattern.java:760)
    at Control.main(Control.java:24)
    Please help me on this issue.
    Thanks&Regards
    Debi
    import java.util.regex.*;
    import java.io.*;
    public class Control {
    public static void main(String[] args)
    throws Exception {
    //Create a file object with the file name
    //in the argument:
    File fin = new File("fileName1");
    File fout = new File("fileName2");
    //Open and input and output stream
    FileInputStream fis =
    new FileInputStream(fin);
    FileOutputStream fos =
    new FileOutputStream(fout);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(fis));
    BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(fos));
         // The pattern matches control characters
    Pattern p = Pattern.compile("{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    //Replaces control characters with an empty
    //string.
    String result = m.replaceAll("");
    out.write(result);
    out.newLine();
    in.close();
    out.close();

    Hi,
    I used the code below with the \p, but I didn't able to complie the file. It gave me an
    D:\Debi\datamigration>javac Control.java
    Control.java:24: illegal escape character
    Pattern p = Pattern.compile("\p{cntrl}");
    ^
    1 error
    Please help me on this issue.
    Thanks&Regards
    Debi
    // The pattern matches control characters
    Pattern p = Pattern.compile("\p{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;

  • How to read characters from a text file in java program ?

    Sir,
    I have to read the characters m to z listed in a text file .
    I must compare the character read from the file.
    And if any of the characters between m to z is matched i have to replace it with a hexadecimal value.
    Any help or suggesstions in this regard would be very useful.
    Thanking you,
    khurram

    Hai,
    The requirement is like this
    There is an input file, the contents of the file are as follows, you can assume any name for the file.
    #Character mappings for Japanese Shift-JIS character set
    #ASCII character Mapped Shift-JIS character
    m 227,128,133 #Half width katakana letter small m
    n 227,128,134 #Half width katakana letter small n
    o 227,129,129
    p 227,129,130
    q 227,129,131
    r 227,129,132
    s 227,129,133
    t 227,129,134
    u 227,129,135
    v 227,129,136
    w 227,129,137
    x 227,129,138
    y 227,129,139
    z 227,129,142
    The contents of the above file are to be read as input.
    On encountering any character between m to z, i have to do a replacement with a hexadecimal code point value for the multibyte representation in the second column in the input file.
    I have the code to get the unicode codepoint value from the multibyte representation, but not from a file.
    So if you could please tell me how to get the characters in the second column, it would be very useful for me.
    The character # is used to represent the beginning of a comment in the input file.
    And comment lines are to be ignored while reading the file.
    Say i have a string str="message";
    then i should replace the m with the unicode code point value.
    Thanking you,
    khurram

  • Need a line feed after 120 characters in a text file

    Hi ,
    I am in the verge of developing a report program which generates a text file (space delimited) for a third party vendor -
    After 80 characters (name field) - I need to have space till 120th position in the record and then the cursor should navigate to the
    the next line (line feed)  in the text file-
    I used several techniques but couldn't succeed u2013 Since there is no characters after 80th position the cursor navigates to the next line or record in the text file u2013  Can anyone help on this regard?
    Thanks in advance.
    Regards
    Rajesh.

    Rajesh,
    Insteadof  differentiating the fields in the text file with SPACE use # or @ as separator and then check by defining a field with length 40 and leave it  blank.
    K.Kiran.

  • Removing unwanted control characters in exported text files

    I am currently evaluating Crystal Reports 2008 to determine applicability to our requirements. I need to export data files to continuous text to be read by other application software. I have successfully created the files but have what I believe to be page feed or end-of-page control characters (small rectangles) in the output. Can someone enlighten me as to how I can suppress or remove these control characters?

    In the export to text options enter 0 for the number of lines per page. This will produce an unpaginated text document without the page control markers.

  • [SOLVED] Why are control characters visible in text files??

    Hi,
    If I direct the output of 'ls' to a file like:
    ls > file.txt
    and open the file in a editor such as vi, joe or mousepad, it looks like this:
    [[01;34m22x22[[0m
    [[01;34m24x24[[0m
    [[01;34m32x32[[0m
    [[0mindex.theme[[0m
    [[01;34mscalable[[0m
    [[m
    I just did the same thing on an old slackware box and no control characters are visible. The same for a recent LFS build. I realize I could probably pipe through dos2unix, but it shouldn't be happening anyway. Any input is appreciated.
    Thanks
    -Frank
    Last edited by fianella (2007-10-24 10:37:00)

    at the DOS prompt (sorry, old habits die hard :-) ) type
    alias ls
    and see what the results are.  Compare that against your slackware or lfs builds.  You will probably find that the color= option is different - most builds will not include the color ANSI sequences if you pipe the output, but if it says color=always the color codes will be included in the redirected file.
    Assuming you find an alias for ls that forces color output, you need to find where that is taking place... in your ~/.bashrc file?  in /etc/profile.d?  And change that to alias ls='ls --color=tty' or something sensible like that.

  • Detecting non printables characters in a text file

    Hi,
    I need to remove some non printable characters like tabs, carriage returns, line feeds,.... and so!
    i want to do something like
    aString.replaceAll(<the non-printable char>, "");

    str = str.replaceAll("\\P{Print}+", "");From http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html, \p{print} is printable characters and \P is the negative of \p.

  • Creating Text files with special characters

    I have a problem writing and then reading special characters in a text file. I am using FileWriter and FileReader and once I write (using FileWriter) in a file.txt many characters with ASCII code less than 31, I can not read them back using FileRead. I simply get a content which is different from the one originally written.
    Does anyone have an idea about this problem ?

    The code is OK, problems may have occured during copy/paste. But in the original code it is written c.
    Here is a copy of the output of those lines that i'm talking about:
    Here is the ASCII Code >> 125
    Here is the ASCII Code >> 126
    Here is the ASCII Code >> 127
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 63
    Here is the ASCII Code >> 160
    Here is the ASCII Code >> 161
    Here is the ASCII Code >> 162

  • Read from Text File - Help Bug?

    Hi - I am currently working on LV8 and I think that there is some misunderstanding potential in the help file. To be more exact in the help to the "Read From Text File" VI.
    The description for "count":
    " ... If count is <0, the function reads the entire file. The
    default is –1, which indicates to read a single line if you placed a checkmark
    next to the Read Lines shortcut menu item and to read the
    entire file if you removed the checkmark next to the item. "
    If count is lower than zero, the function reads the entire file. That sounds clear to me.
    The default is -1, which indicates to read a single line if you placed a checkmark next to the "Read Lines" shortcut menu item. Now what? Does it read a single line or the whole file?
    .. and to read the entire file if you removed the checkmark next to the item. I thought it reads the whole file if I use -1 ?
    the VI itself behaves as I'd expect it to:
    * If I place a checkmark next to Read Lines and put -1, I get an array containing the lines
    * If I remove the checkmark, I get only a single string item.
    Now where is the error? Is the VI not working properly or only the description a little bit ... strange ?

    ?hein??
    ?what?
    Both you guys lost me..
    And I drink coffee without sugar (being sweet enough, already) 
    Here is what I get from Context Help on the Read From Text File:
    Read from Text File
    Reads a specified number of characters or lines from a byte stream file. By default, this function reads all characters from the text file. Wire an integer value to count to specify how many individual characters you want to read starting with the first character. Right-click the function and place a checkmark next to the Read Lines option in the shortcut menu to read individual lines from the text file. When you select the Read Lines option in the shortcut menu, wire an integer value to the count input to specify how many individual lines you want to read from the file starting with the first line. Enter a value of -1 in count to read all characters and lines from the text file.
    Humm.
    New feature (again)..  If you select checkmark the Read Lines option, it will not send the text to a sting indicator, as shown in the attached image.  If selected, then it's expecting to write lines to an array of strings...  WHY???  I don't know..  I'll ask..
    Strange...  LV8 is full of mysteries... 
    RayR
    Attachments:
    bad write file.JPG ‏33 KB
    more bad write file.JPG ‏12 KB

  • How to print a text file using Java

    How can I print a text file using Java without converting the output to an image format. Is there anyway I can send the characters in the text file as it is for a print job? I did get a listing doing this ... but that converted the text to an image format before printing....
    THanks,.

    Hi I had to write a print api from scratch, and I did not convert the output to image. Go and read up on the following code. I know there is a Tutorial on Sun about the differant sections of the snippet.
    private void printReport()
         Frame tempFrame = new Frame(getName());
         PrintJob printerJob = Toolkit.getDefaultToolkit().getPrintJob(tempFrame, "Liesltext", null);
         Graphics g = printerJob.getGraphics();
                    //I wrote the method below for calculations
         printBasics(g);
         g.dispose();
         printerJob.end();
    }This alone wont print it you have to do all the calculations in the printBasics method. And as I said I wrote this from scratch and all I did was research first the tutorial and the white papers
    Ciao

  • Extra space adding during spool data into text file

    I'm using sql developer to query oracle tables. I can export data using GUI of sql developer, but I wish to use spool query to export the data. Using below query, I was able to export the data to specified location, but my final text file consist of additional spaces after each line. These additional spaces between each line is causing an error to upload the text file in different location.
    Did any one face have this issue? Below is my query
    set head off
    SET FEEDBACK OFF
    SET ECHO    OFF
    SET TRIMSPOOL ON
    SET TRIMOUT ON
    spool c:\test.txt
    select cast(memberid||',12'as varchar2(20))
    from abc;
    spool off
    set head on
    set ECHO on
    i'm using trimspool, and trimout, but it is not removing any blank spaces.

    Sorry, I changed my export.sql to the query you provided.
    SET HEAD OFF FEED OFF ECHO OFF
    SET LIN 120 PAGES 0 TRIMS ON
    SPOOL c:\test.txt
    SELECT memberid || ',12' FROM abc;
    SPOOL OFF
    But,the spool query is still adding additional spaces making length of each line 43 characters in final text file output.

  • How to read text file contain chinese character ?

    Hi XI Expert,
    I have scenario to read text file contain Chinese Character using sender file adapter. but every i was check from sxmb_moni all the chinese character looks different. and also the target file also i has changes.
    Please advise me how to maintaine the chinese character in PI 7.0 SP17.
    Thank You and Best Regards
    Fernand

    Hi,
    Refer these threads..
    Receiver file adapter corrupting characters
    Problem in converting special characters in input text file
    Here is one more useful guide..
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/502991a2-45d9-2910-d99f-8aba5d79fb42
    Regards,
    Sarvesh
    Edited by: Sarvesh Singh on Nov 17, 2008 3:47 PM

  • Java newbie & text files

    I want to create a simple program that will read a text file and put it in a variable to use later in the program. I can't figure out how to assign characters from the text file to a variable. Please bear with me, this is my latest attempt:
    import java.io.*;
    public class FileReader1 {
    public static void main(String[] args) throws IOException {
         File inputFile = new File("nfo.txt");
    FileReader in = new FileReader(inputFile);
    String intext;
    int c;
    while ((c = in.read()) != -1)
    intext = (String)in;
    in.close();
    System.out.println(intext);
    }

    I used the BufferedReader method on the FileReader method to get a string instead of characters, thus I could easily assign the value to a string variable. Below is my solution:
    import java.io.*;
    public class FileReader1 {
    public static void main(String[] args) throws IOException {
         File inputFile = new File("nfo.txt");
    FileReader in = new FileReader(inputFile);
              BufferedReader br = new BufferedReader(in);
              String s;
              String intext="";
    while ((s = br.readLine()) != null)
              intext = s;
    System.out.println(intext);
    in.close();
    }

Maybe you are looking for