Issue : Read a text file and print the same

Hi, My requirement is to read a text file and print it the same way.
import java.io.BufferedReader;
import java.io.FileReader;
public class CatFile {
public static void main(String[] args) throws Exception
     FileReader file = new FileReader("D:/Test/Allfiles.txt");
     BufferedReader reader = new BufferedReader(file);
     String text = "";
     String line = reader.readLine();
     while (line != null)
          text += line;
          line = reader.readLine();
     System.out.println(text);
The text file i used contains
A
B
C
but my output is ABC.
What change should be made to print it the same way in the txt file ?

Hi EJP,
I modified the code based on your suggestion and now its working as expected. Thanks
Modified code :
import java.io.BufferedReader;
import java.io.FileReader;
public class CatFile {
public static void main(String[] args) throws Exception
     FileReader file = new FileReader("D:/Test/Allfiles.txt");
     BufferedReader reader = new BufferedReader(file);
     String text = "";
     String line = reader.readLine();
     while (line != null)
          System.out.println(line);
          line = reader.readLine();
          text += line;
}

Similar Messages

  • Want to update a text file and reflect the same on iview immediately

    Dear friends,
    I have a text file in a repository path
    I could read each line and do some task.
    My query is for each line task, i would like to update a file (for me it is log file) and reflec the same on a iview in the same page
    sample code appreciated
    regards
    Kantha

    If the user backs up their device to either iCloud or Mac/PC, they can restore the app data from that backup.
    There's no need to do what you intend.

  • Searching a text file and printing the line if found!

    Hi, Im fairly new to JAVA and have been googling this for hours and havent found any results that
    have helped me...
    Im looking to search a text file for a value that is in a that is delimited by colons
    eg 45787 : 398948 : 398884 : 398984
    IF that value is found I need to print this entire line and move it into a string.
    I can work out the delimit part, the problem for me is a)searching the text file
    and b) tell java to print that line only??
    Any help would be very very much appreciated
    Cheers
    James

      public void printCourses() throws Exception
                stuinput[] courseObjArray = new stuinput[10]; //Make sure this is the same as the ammount in the text
                   Scanner sc = new Scanner(new File("testfile.txt"));
                   int i=0;
                   boolean found = false;
                   while(sc.hasNextLine())
                   //Delimit this line with scanner
                   Scanner sc1 = new Scanner(sc.nextLine());
                   sc1.useDelimiter(":");
                   courseObjArray[i] = new stuinput(sc1.next(),sc1.next());
                   i++;
                   }//while
                   for(int i1 = 0;i1 < courseObjArray.length;i1++)
                   System.out.println(courseObjArray[i1].courseCode);
                   System.out.println(courseObjArray[i1].courseName);
                   System.out.println(courseObjArray[i1].courseName);
                   System.out.println("-----------------");     
                   String courseCode2 = "courseObjArray[i1].courseCode";
                   if (courseCode2  == "12345")
                        System.out.println("working");
                   else{System.out.println("Not Found");}
           }hmmm just wondering why could this method always return a "Not Found"....if the text file had a whole bunch of values like this
    12345:Course1
    12344:Course2
    12343:Course3
    isnt it surposed to return 1 "Working"?? because there is a 12345 in on of the line, in the semi colon delimited line with 2 values, one being the course code, one being the course name??
    Given that there is 10 lines (from Array Object)

  • Convert XML to text file and sending the same via Mail receiver adapter

    Dear All,
    I have a requirement like....
    I am getting a XML file as a result of mapping and it needs to be converted to a TEXT file and
    the converted file needs to be sent to a mail address in text format.
    Any body has idea how to achieve this?
    Thanks in advance for your help.
    Regards
    Hari

    >
    HP CReddy wrote:
    > Dear All,
    >
    > I have a requirement like....
    >
    > I am getting a XML file as a result of mapping and it needs to be converted to a TEXT file and
    > the converted file needs to be sent to a mail address in text format.
    >
    > Any body has idea how to achieve this?
    >
    > Thanks in advance for your help.
    >
    > Regards
    > Hari
    use the StructXML2Plain or XML2Plain from the standard MessageTransformBean
    Add the module to you Mail adapter before the mail adapters standard module itself
    Ref: http://help.sap.com/saphelp_nw04/helpdata/en/24/4cad3baabd4737bab64d0201bc0c6c/content.htm

  • Read a text file and put the text in a TextEdit UI

    I have found code sample for reading file inside webdynpro, but I can't manage to make it works with a text file on the web (ex.: "http:/.../file.txt").
    Can someone post the exact code needed for that?
    Thanks!

    Hope this post will help people doing their homeworks...
              StringBuffer tmpBuffer = new StringBuffer();
              try {
                   URL url = new URL("http://.../test.txt");
                   URLConnection urlconnection = url.openConnection();
                   long l = urlconnection.getContentLength();
                   tmpBuffer.append("Content Length = " + l);
                   BufferedReader in =
                        new BufferedReader(new InputStreamReader(url.openStream()));
                   String line;
                   while ((line = in.readLine()) != null) {
                        tmpBuffer.append("\n" + line);
                   in.close();
              } catch (Exception e) {
                   //System.out.println(e.toString());
              if (tmpBuffer != null) {
                   wdContext.currentContextElement().setZoneMessage(
                        tmpBuffer.toString());

  • How can i read the text files and buffer the data in Vector?

    hi. I have been running into this problem for days, but with no luck and losing right direction.
    The problem is : I am trying to read a text file and buffer the data into a
    Queue for each user.
    the sample text file is as below:( 1st column is timestamp, 2nd is user_id, 3rd is packet_id, 4th is packet_seqno, 5th is packet_size)
    0 1 1 1 512
    1 2 1 2 512
    2 3 1 3 512
    3 4 1 4 512
    4 5 1 5 512
    5 6 1 6 512
    6 7 1 7 512
    7 8 1 8 512
    8 9 1 9 512
    9 10 1 10 512
    10 1 2 11 512
    11 2 2 12 512
    12 3 2 13 512
    13 4 2 14 512
    14 5 2 15 512
    15 6 2 16 512
    16 7 2 17 512
    17 8 2 18 512
    18 9 2 19 512
    19 10 2 20 512
    20 1 3 21 512
    21 2 3 22 512
    22 3 3 23 512
    23 4 3 24 512
    24 5 3 25 512
    25 6 3 26 512
    26 7 3 27 512
    27 8 3 28 512
    28 9 3 29 512
    29 10 3 30 512
    30 1 4 31 512
    31 2 4 32 512
    32 3 4 33 512
    33 4 4 34 512
    34 5 4 35 512
    35 6 4 36 512
    36 7 4 37 512
    37 8 4 38 512
    38 9 4 39 512
    39 10 4 40 512
    40 1 5 41 512
    41 2 5 42 512
    42 3 5 43 512
    43 4 5 44 512
    44 5 5 45 512
    45 6 5 46 512
    46 7 5 47 512
    47 8 5 48 512
    48 9 5 49 512
    49 10 5 50 512
    50 1 6 51 512
    51 2 6 52 512
    52 3 6 53 512
    53 4 6 54 512
    54 5 6 55 512
    55 6 6 56 512
    56 7 6 57 512
    57 8 6 58 512
    58 9 6 59 512
    59 10 6 60 512
    60 1 7 61 512
    61 2 7 62 512
    62 3 7 63 512
    63 4 7 64 512
    64 5 7 65 512
    65 6 7 66 512
    66 7 7 67 512
    67 8 7 68 512
    68 9 7 69 512
    69 10 7 70 512
    70 1 8 71 512
    71 2 8 72 512
    What I wanna do is to read all the data above and buffer them in a queue for each user( there are only 10 users in total).
    I already created a class called Class packet:
    public class packet {
        private int timestamp;
        private int user_id;
        private int packet_id;
        private int packet_seqno;
        private int packet_size;
        /** Creates a new instance of packet */
        public packet(int timestamp,int user_id, int packet_id,int packet_seqno, int packet_size)
            this.timestamp = timestamp;
            this.user_id=user_id;
            this.packet_id=packet_id;
            this.packet_seqno=packet_seqno;
            this.packet_size=packet_size;
    }then I wanna to create another Class called Class user which I can create a queue for each user (10 users in total) to store type packet information. the queue for each user will be in the order by timestamp.
    any idea and sample code will be appreciated.

    Doesn't sound too hard to me. Your class User (the convention says to capitalize class names) will have an ArrayList or Vector in it to represent the queue, and a method to store a Packet object into the List. An array or ArrayList or Vector will hold the 10 user objects. You will find the right user object from packet.user_id and call the method.
    Please try to write some code yourself. You won't learn anything from having someone else write it for you. Look at sample code using ArrayList and Vector, there's plenty out there. Post in the forum again if your code turns out not to behave.

  • Read multiple text files and sort them

    I am trying to read multiple text files and store the data from the file in vector.
    but for days. I am with no luck. anyone can help me out with it? any idea of how to sort them will be appreciated.
    Below is part of the code I implemented.
    public class packet {
        private int timestamp;
        private int user_id;
        private int packet_id;
        private int packet_seqno;
        private int packet_size;
        public packet(int timestamp0,int user_id0, int packet_id0,int packet_seqno0, int packet_size0)
            timestamp = timestamp0;
            user_id=user_id0;
            packet_id=packet_id0;
            packet_seqno=packet_seqno0;
            packet_size=packet_size0;
        public void setTime(int atimestamp)
            this.timestamp=atimestamp;
        public void setUserid(int auserid)
            this.user_id=auserid;
        public void setPacketid(int apacketid)
            this.packet_id=apacketid;
        public void setPacketseqno(int apacketseqno)
            this.packet_seqno=apacketseqno;
        public void setPacketsize(int apacketsize)
            this.packet_size=apacketsize;
        public String toString()
            return timestamp+"\t"+user_id+"\t"+packet_id+"\t"+packet_seqno+"\t"+packet_size+"\t";
    }Here is the data from part of the text files. ( the first column is timestamp, second is userid, third is packetid.....)
    0 1 1 1 512
    1 2 1 2 512
    2 3 1 3 512
    3 4 1 4 512
    4 5 1 5 512
    5 6 1 6 512
    6 7 1 7 512
    7 8 1 8 512
    8 9 1 9 512
    9 10 1 10 512
    10 1 2 11 512
    11 2 2 12 512
    12 3 2 13 512
    13 4 2 14 512
    14 5 2 15 512
    15 6 2 16 512
    16 7 2 17 512

    Here's a standard idiom for object-list-sorting:
    /* cnleafdata.txt *********************************************
    0 1 1 1 512
    1 2 1 2 512
    2 3 1 3 512
    3 4 1 4 512
    4 5 1 5 512
    5 6 1 6 512
    6 7 1 7 512
    7 8 1 8 512
    8 9 1 9 512
    9 10 1 10 512
    10 1 2 11 512
    11 2 2 12 512
    12 3 2 13 512
    13 4 2 14 512
    14 5 2 15 512
    15 6 2 16 512
    16 7 2 17 512
    import java.util.*;
    import java.io.*;
    public class Packet implements Comparable<Packet>{
      private int timeStamp;
      private int userId;
      private int packetId;
      private int packetSeqno;
      private int packetSize;
      public Packet(int timeStamp0, int userId0, int packetId0,
       int packetSeqno0, int packetSize0) {
        timeStamp = timeStamp0;
        userId = userId0;
        packetId = packetId0;
        packetSeqno = packetSeqno0;
        packetSize = packetSize0;
      public Packet(String timeStamp0, String userId0, String packetId0,
       String packetSeqno0, String packetSize0) {
        this(Integer.parseInt(timeStamp0), Integer.parseInt(userId0),
         Integer.parseInt(packetId0), Integer.parseInt(packetSeqno0),
         Integer.parseInt(packetSize0));
      public Packet(String[] a){
        this(a[0], a[1], a[2], a[3], a[4]);
      public void setTime(int aTimeStamp){
        timeStamp = aTimeStamp;
      public void setUserId(int aUserId){
        userId = aUserId;
      public void setPacketId(int aPacketId){
        packetId = aPacketId;
      public void setPacketSeqno(int aPacketSeqno){
        packetSeqno = aPacketSeqno;
      public void setPacketSize(int aPacketSize){
        packetSize = aPacketSize;
      public int getUserId(){
        return userId;
      public String toString(){
        return String.format
    ("%2d %2d %2d %2d %4d", timeStamp, userId, packetId, packetSeqno, packetSize);
      public int compareTo(Packet otherPacket){
        return userId - otherPacket.getUserId();
      /* main for test */
      public static void main(String[] args){
        String line;
        ArrayList<Packet> alp;
        alp = new ArrayList<Packet>();
        try{
          BufferedReader br = new BufferedReader(new FileReader("cnleafdata.txt"));
          while ((line = br.readLine()) != null){
            // if (! recordValid(line)){
            //   continue;
            String[] ar = line.split("\\s");
            alp.add(new Packet(ar));
        catch (Exception e){
          e.printStackTrace();
        System.out.println("[original]");
        for (Packet p : alp){
          System.out.println(p);
        System.out.println();
        Collections.sort(alp);
        System.out.println("[sorted by user ID]");
        for (Packet p : alp){
          System.out.println(p);
    }

  • Reading a text file and putting it in a textarea

    hi can u tell me how to read a text file and display the contents in a text area using jsp please?
    thanks :o)

    <%@ page import="java.sql.*, java.io.*" %>
    <HTML>
    <HEAD>
         <TITLE>User Application Area</TITLE>
    <SCRIPT LANGUAGE="javascript" SRC="cal2.js">
    </SCRIPT>
    <SCRIPT LANGUAGE="javascript" SRC="cal_conf2.js"></SCRIPT>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
    <%
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:fypproject","","");
    Statement st = con.createStatement();
    String email = (String)session.getAttribute("email");
    String levelStatus = (String)session.getAttribute("levelStatus");
    String details = "SELECT PD.Forename, PD.Surname, L.Level_Name FROM Personal_Details PD,
    Login_Details LD, Levels L WHERE PD.Email_Address = '" + email + "' AND PD.Email_Address =
    LD.Email_Address AND LD.Level_ID = '" + levelStatus + "' AND LD.Level_ID = L.Level_ID";
    ResultSet rsDet = st.executeQuery(details);
    if(rsDet.next()) {
    String forename = rsDet.getString("Forename");
    String surname = rsDet.getString("Surname");
    String levelName = rsDet.getString("Level_Name");
    %>
    <DIV ALIGN="center"><H1>User Application Arena</H1></DIV>
    <BR>
    <H4>Welcome back <% out.println(forename + " " + surname); %> </H4>
    <BR>
    Your status is:
    <FONT COLOR = "red">
    <% out.println(levelName); %>
    </FONT>
    <BR>
    <%
    if(levelStatus.compareTo("0")==0) {
    %>
    <BR>
    <DIV ALIGN="center">
    Please come back later and re-check your status to see if your application has progressed. If it has
    been more than a week since you submitted it please phone the HR department on 020 7123 4567
    <BR><BR>
    Log Out
    </DIV>
    </FORM>
    <%
    else if(levelStatus.compareTo("1")==0) {
    %>
    <FORM NAME="sampleform" ACTION="ProcessInterview.jsp">
    <DIV ALIGN="center">
    Congratulations, we would like to invite you for a First Round tests and interview. Please select a
    date that would suit you on our online calendar below
    <BR><BR>
    <SMALL>PLEASE CLICK HERE TO SELECT A DATE</SMALL>
    <BR><BR>
    <INPUT TYPE="text" NAME="firstinput" SIZE=20>
    <BR><BR>
    <INPUT TYPE="submit" VALUE="Confirm">
    </DIV>
    </FORM>
    <%
    else if(levelStatus.compareTo("2")==0) {
    %>
    <FORM NAME="sampleform" ACTION="ProcessInterview.jsp">
    <DIV ALIGN="center">
    Congratulations, we would like to invite you for a Second Round interview. Please select a date that
    would suit you on our online calendar below
    <BR><BR>
    <SMALL>PLEASE CLICK HERE TO SELECT A DATE</SMALL>
    <BR><BR>
    <INPUT TYPE="text" NAME="firstinput" SIZE=20>
    <BR><BR>
    <INPUT TYPE="submit" VALUE="Confirm">
    </DIV>
    </FORM>
    <%
    else if(levelStatus.compareTo("3")==0) {
    File inFile = new File("offer.txt");
    StringBuffer sb = new StringBuffer();
    BufferedReader buf = new BufferedReader(new FileReader(inFile));
    while (buf.ready()) {       
    sb.append(buf.readLine());
    buf.close();
    %>
    <TEXTAREA NAME ="text" ROWS="10" COLS="60">
    <%= sb.toString() %>
    </TEXTAREA>
    <%
    else if(levelStatus.compareTo("4")==0) {
    out.println("send rej email");
    st.close();
    con.close();
    %>
    </BODY>
    </HTML>
    THANKS!! :o)

  • To upload a RTF and a PDF file to SAP R/3 and print the same through SAP

    Hi,
    I have a requirement to upload a PDF file and a RTF file to SAP R/3 and print the same.
    I wrote the following code for uploading a RTF file to SAP R/3 and print the same. However, the problem is , the formatting present in the RTF document( bold/italics..etc) is not being reflected when I do the 'print-preview' after the executing the code below :
    report z_test_upload .
    data: begin of itab occurs 0,
             rec type string,
          end of itab.
    data: options like itcpo.
    data: filename type string,
          count type i.
    data: filetype(10) type c value 'ASC'.
    DATA: HEADER  LIKE THEAD    OCCURS   0 WITH HEADER LINE.
    DATA: NEWHEADER  LIKE THEAD    OCCURS   0 WITH HEADER LINE.
    DATA: ITFLINE LIKE TLINE    OCCURS   0 WITH HEADER LINE.
    DATA: RTFLINE LIKE HELP_STFA OCCURS   0 WITH HEADER LINE.
    DATA:   string_len TYPE i,
            n1 TYPE i.
    selection-screen begin of block b1.
      parameter: p_file1(128) default 'C:\test_itf.rtf'.
    selection-screen end of block b1.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file1.
      CALL FUNCTION 'F4_FILENAME'
           IMPORTING
                file_name = p_file1.
    start-of-selection.
    move p_file1 to filename.
    call function 'GUI_UPLOAD'
         EXPORTING
              filename                = filename
              filetype                = filetype
         TABLES
              data_tab                = itab
         EXCEPTIONS
              file_open_error         = 1
              file_read_error         = 2
              no_batch                = 3
              gui_refuse_filetransfer = 4
              invalid_type            = 5
              no_authority            = 6
              unknown_error           = 7
              bad_data_format         = 8
              header_not_allowed      = 9
              separator_not_allowed   = 10
              header_too_long         = 11
              unknown_dp_error        = 12
              access_denied           = 13
              dp_out_of_memory        = 14
              disk_full               = 15
              dp_timeout              = 16
              others                  = 17.
    if sy-subrc <> 0.
      message id sy-msgid type sy-msgty number sy-msgno
                with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    endif.
    loop at itab.
      string_len = strlen( itab-rec ).
      n1 = string_len DIV 134.
      ADD 1 TO n1.
      DO n1 TIMES.
        rtfline-line = itab-rec.
        APPEND rtfline.
        SHIFT itab-rec BY 134 PLACES.
      ENDDO.
    endloop.
    HEADER-TDSTYLE = 'S_DOCUS1'.
    HEADER-TDFORM = 'S_DOCU_SHOW'.
    header-tdspras = 'E'.
    CALL FUNCTION 'CONVERT_TEXT'
      EXPORTING
      CODEPAGE               = '0000'
        DIRECTION              = 'IMPORT'
        FORMAT_TYPE            = 'RTF'
       FORMATWIDTH            = 72
        HEADER                 = header
        SSHEET                 = 'WINHELP.DOT'
        WITH_TAB               = 'X'
        WORD_LANGU             = SY-LANGU
        TABLETYPE              = 'ASC'
      TAB_SUBSTITUTE         = 'X09  '
      LF_SUBSTITUTE          = ' '
      REPLACE_SYMBOLS        = 'X'
      REPLACE_SAPCHARS       = 'X'
      MASK_BRACKETS          = 'X'
      IMPORTING
        NEWHEADER              = NEWHEADER
      WITH_TAB_E             =
      FORMATWIDTH_E          =
      TABLES
        FOREIGN                = RTFLINE
        ITF_LINES              = ITFLINE.
      LINKS_TO_CONVERT       =
    if sy-subrc <> 0.
    endif.
    CALL FUNCTION 'PRINT_TEXT_ITF'
      EXPORTING
         HEADER        = newheader
         OPTIONS       = options
    IMPORTING
      RESULT        =
      TABLES
        LINES         = itfline.
    if sy-subrc <> 0.
    endif.
    Any hints or suggestions to solve this problem will be highly appreciated.
    Thanks,
    Avra

    Hi Vishwas,
    Check out the thread [Efficient way of saving documents uploaded|Re: Efficient way of saving documents uploaded by users; and check the blog by Raja Thangamani.
    Also check the thread [Export Images through Function Modules   |Export Images through Function Modules;.
    Hope it helps you.

  • Read a text file and populate table

    My email addres is [email protected]
    I am new to java. My project requires me to read a text file and pick some values from the text file and populate a table in MS Access. The main fields are from the TEXT. Some of the columns to be read are:
    Transaction ref.
    Amount
    User ref.
    Date
    The text file is as follows:
    Receiver =
    FBNINGLAXXX LT : A
    FST BANK OF NIGERIA PLC
    LAGOS
    LAGOS
    NG
    NIGERIA
    Transaction ref. = SPLOUK01P0008888 Related ref. = 00077003
    Amount = 16675750, NGN Value/Date =
    Format & Validation
    Version = 0205 Checked = Minimum
    Netw. Appl. = FIN Passed = Minimum
    Sender to Receiver Instructions
    Banking Prior. = User ref. = SPLOUK01P0008888
    Warning Status =
    Possible Duplicate Emission
    Appl/Serv = SWIFT Interface
    RP & Ft = SIfrom_SWIFT
    Date/Time = 01/04/03 18:53:19
    Text =
    :20:SPLOUK01P0008888
    :28D:1/1
    :30:030401
    :21:00077003
    :32B:NGN16675750,00
    :50H:/4072010014877
    SPDC FBN East Main A/C
    :57D:WEMA BANK PLC
    PLOT 22 TRANS-AMADI BRANCH P.H.
    PORT HARCOURT.
    RIVERS STATE.
    :59:/0421002101818
    PROJECT MASTERS NIGERIA LTD.
    C101 ELIOGBOLO VILLAGE OFF
    EAST-WEST ROAD RUMUOKORO PORT HAR
    COURT
    :70:PM PCE-TS 03 001030226
    :71A:OUR
    Block 5:
    {MAC:9F664844}{CHK:60EF6513E579}
    Message History =
    *Original (Completed)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    See in this case as you are dealing with Files and database. you need read the File by using the I/O Streams. if you have to select some particular values you can go Random access file.Once you have retrived values. You can go for the second part that is make a jdbc connection to database, and use simple SQL statements to populate those values into the table.
    How this will give you a better picture

  • Reading a text file and transferring values into array

    Hi,
    I have a problem. So what I am trying to do is that, I read a text file and insert specific values from the text file into an array for future needs.
    But I have to make sure that there is no duplicate entries. So thats what I have but, my method takes forever to finish...
    here is my code:
    String nomFichier = "Test_" + numTest + "_" + date + ".txt";
            String ligne = "";
            int z = 0;
            int j = 0;
            BufferedReader lecteurFichier = new BufferedReader(new FileReader(nomFichier));
            while ((ligne = lecteurFichier.readLine()) != null) {
                if (z > 3)
                    String valeur = "";
                    String dist = "";
                    boolean unique = true;
                    String [] chiffre = ligne.split(";");
                     if (intervalleAnalyser == 1)
                        valeur = chiffre[3];
                        dist = chiffre[4];
                    if (intervalleAnalyser == 2)
                        valeur = chiffre[2];
                        dist = chiffre[4];
                    if (intervalleAnalyser == 3)
                        valeur = chiffre[1];
                        dist = chiffre[4];
                    if (z == 4) {
                        intervalleDiagramme[j] = valeur;
                        j++;
                    if (z > 4) {
                        for (int i = 0; i < intervalleDiagramme.length; i++)
                             for (int x = 0; x < i; x++)
                                 if(intervalleDiagramme[i] == intervalleDiagramme[x])
                                    unique = false;
                        if (unique)
                            intervalleDiagramme[j] = valeur;
                        j++;
                z++;
            lecteurFichier.close(); // toujours fermer le fichier

    Hi,
    Thanks for your reply,
    1) Yeah I have a method that asks the question and assigns it to a variable.
    2) Well the z will stop once there is no lines to read no?
    for the set.add(), I am not that familar...
    I changed bit a code and I have this now:
    if (z > 4) {
                        for (int i = 0; i < intervalleDiagramme.length; i++)
                            System.out.println(intervalleDiagramme);
    if(intervalleDiagramme[i].equals(valeur))
    System.out.println(intervalleDiagramme[i] + " " + valeur);
    unique = false;
    if (unique)
    intervalleDiagramme[j] = valeur;
    EDIT:
    I figured a way to assign " " to all the values in my array. But I get this error:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 380
    at TP3.lireFichier(TP3.java:305)
    And my line 305 is: intervalleDiagramme[j] = valeur;
    EDIT2:
    So ok I found my mistake and corrected it. But I want to know is there a way of doing this without setting the size of the array? because sometimes there needs to be 21 values sometimes 19 and sometimes 20....
    If I take out: = new String [21] out I get a NullPointer error...
    Edited by: Ara1992Habs on Dec 13, 2009 7:29 AM
    Edited by: Ara1992Habs on Dec 13, 2009 7:37 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • I would like to read a text file in which the decimal numbers are using dots instead of commas. Is there a way of converting this in labVIEW, or how can I get the program to enterpret the figures in the correct way?

    The program doest enterpret my figures from the text file in the correct way since the numbers contain dots instead of commas. Is there a way to fix this in labVIEW, or do I have to change the files before reading them in the program? Thanks beforehend!

    You must go in the labview option menu, you can select 'use the local
    separator' in the front side submenu (LV6i).
    If you use the "From Exponential/Fract/Eng" vi, you are able to select this
    opton (with a boolean) without changing the labview parameters.
    (sorry for my english)
    Lange Jerome
    FRANCE
    "Nina" a ecrit dans le message news:
    [email protected]..
    > I would like to read a text file in which the decimal numbers are
    > using dots instead of commas. Is there a way of converting this in
    > labVIEW, or how can I get the program to enterpret the figures in the
    > correct way?
    >
    > The program doest enterpret my figures from the text file in the
    > correct way since the numbers contain dots instea
    d of commas. Is there
    > a way to fix this in labVIEW, or do I have to change the files before
    > reading them in the program? Thanks beforehend!

  • How to read the contents of a text file and populate the data in a table ?

    Hello All,
      Can anyone advise on how to acheieve the above ? I am trying to read in a text file (CSV) and have the contents populated to the respective UI elements in a table. Any help is greatly appreciated.
    from
    Kwok Wei

    Hi,
    Let us consider you have list of names(Seperated by delimeter) in a text file and you want to display in  a table.
    1. Create Context Node "Names" and context attribute "Name"
    2. Create Table and bind to the above context.
    3.Write the following code in the "Init method.
    try{
    FileReader f =new FileReader("");
    BufferedReader r=new BufferedReader(f);
    String names=r.readLine();
    Vector Names=new Vector();
    // Use Tokenizer and store all the names i a vector//
    for(int i=0;i<Names.size();i++){
    IPrivate<<VieName>>.INameElement ele=wdContext.createNameElement();
    ele.set<<Name>>( Names.get(i).toString());
    wdContext.NodeName().addElement(ele);
    Regards, Anilkumar
    Message was edited by: Anilkumar Vippagunta

  • Where does this java program read a text file and how does it output the re

    someone sent this to me. its a generic translator where it reads a hashmap text file which has the replacement vocabulary etc... and then reads another text file that has what you want translated and then outputs translation. what i don't understand is where i need to plugin the name of the text files and what is the very first line of code?
    [code
    package forums;
    //references:
    //http://forums.techguy.org/development/570048-need-write-java-program-convert.html
    //http://www.wellho.net/resources/ex.php4?item=j714/Hmap.java
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class Translate {
    public static void main(String [] args) throws IOException {
    if (args.length != 2) {
    System.err.println("usage: Translate wordmapfile textfile");
    System.exit(1);
    try {
    HashMap words = ReadHashMapFromFile(args[0]);
    System.out.println(ProcessFile(words, args[1]));
    } catch (Exception e) {
    e.printStackTrace();
    // static helper methods
    * Reads a file into a HashMap. The file should contain lines of the format
    * "key\tvalue\n"
    * @returns a hashmap of the given file
    @SuppressWarnings("unchecked")
    private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    HashMap map = null;
    try {
    in = new BufferedReader(new FileReader(filename));
    String line;
    map = new HashMap();
    while ((line = in.readLine()) != null) {
    String[] fields = line.split("\\t", 2);
    if (fields.length != 2) continue; //just ignore "invalid" lines
    map.put(fields[0], fields[1]);
    } finally {
    if(in!=null) in.close(); //may throw IOException
    return(map); //returning a reference to local variable is safe in java (unlike C/C++)
    * Process the given file
    * @returns String contains the whole file.
    private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    StringBuffer out = null;
    try {
    in = new BufferedReader(new FileReader(filename));
    out = new StringBuffer();
    String line = null;
    while( (line=in.readLine()) != null ) {
    out.append(SearchAndReplaceWordsInText(words, line)+"\n");
    } finally {
    if(in!=null) in.close(); //may throw IOException
    return out.toString();
    * Replaces all occurrences in text of each key in words with it's value.
    * @returns String
    private static String SearchAndReplaceWordsInText(Map words, String text) {
    Iterator it = words.keySet().iterator();
    while( it.hasNext() ) {
    String key = (String)it.next();
    text = text.replaceAll("\\b"+key+"\\b", (String)words.get(key));
    return text;
    * @returns: s with the first letter capitalized
    String capitalize(String s)
    return s.substring(0,0).toUpperCase() + s.substring(1);
    }

    without what arguments?Without any arguments. If there are no arguments, there are no arguments of any kind. If you have a zoo with no animals in it, it's not meaningful to ask whether the animals which are not there are zebras or elephants.
    does it prompt me to give it a text file name?Apparently.
    when i run it this is all i get:
    usage: Translate wordmapfile textfile
    Press any key to continue...Right. And "wordmapfile" is almost certainly supposed to be a file that holds the word map, and "textfile" is almost certainly the file of text that it's going to translate.

  • Reading from a text file and displaying the contents with in a frame

    Hi All,
    I am trying to read some data from a text file and display it on a AWT Frame. The contents of the text file are as follows:
    pcode1,pname1,price1,sname1,
    pcode2,pname2,price2,sname1,
    I am writing a method to read the contents from a text file and store them into a string by using FileInputStream and InputStreamReader.
    Now I am dividing the string(which has the contents of the text file) into tokens using the StringTokenizer class. The method is as show below
    void ReadTextFile()
                        FileInputStream fis=new FileInputStream(new File("nieman.txt"));
                         InputStreamReader isr=new InputStreamReader(fis);
                         char[] buf=new char[1024];
                         isr.read(buf,0,1024);
                         fstr=new String(buf);
                         String Tokenizer st=new StringTokenizer(fstr,",");
                         while(st.hasMoreTokens())
                                          pcode1=st.nextToken();
                               pname1=st.nextToken();
              price1=st.nextToken();
                              sname1=st.nextToken();
         } //close of while loop
                    } //close of methodHere goes my problem: I am unable to display the values of pcode1,pname1,price1,sname1 when I am trying to access them from outside the ReadTextFile method as they are storing "null" values . I want to create a persistent string variable so that I can access the contents of the string variable from anywhere with in the java file. Please provide your comments for this problem as early as possible.
    Thanks in advance.

    If pcode1,pname1,price1,sname1 are global variables, which I assume they are, then simply put the word static in front of them. That way, any class in your file can access those values by simply using this notation:
    MyClassName.pcode1;
    MyClassName.pname1;
    MyClassName.price1;
    MyClassName.sname1

Maybe you are looking for