Reading a text file and storing its data as a 2D array.

I am creating a high score class for a game I am building which stores the top ten scores (NAME and SCORE) in a text file. The text file will have no more than a list of 10 rows and 2 columns so a 2d array of [1][9] will suffice.
My aim is to create a 2D array that can be sorted depending on scores but thats not the difficult bit.
I know that I have to read in each line of the text file individually and have managed to do that successfully in my code so far.
     public void readScores()
          try
               FileReader ifile = new FileReader("listOfHighScores.txt");
               BufferedReader bufStream = new BufferedReader(ifile);
               String positionOne = bufStream.readLine();
               String positionTwo = bufStream.readLine();
               String positionThree = bufStream.readLine();
               String positionFour = bufStream.readLine();
               String positionFive = bufStream.readLine();
               String positionSix = bufStream.readLine();
               String positionSeven = bufStream.readLine();
               String positionEight = bufStream.readLine();
               String positionNine = bufStream.readLine();
               String positionTen = bufStream.readLine();
               bufStream.close();
          catch (IOException e)
               JOptionPane.showMessageDialog
                    (null, "AN ERROR HAS OCCURRED");
     }It's the actual inputting the data into a 2D array thats proving rather difficult for me. I'm looking into using String Tokenizer to split up the lines of the text file which looks as follows but after reading several text books am still puzzled as to how it actually works:
300 James
290 Bob
280 Gareth
270 Steve
260 Nick
250 Fred
240 Ryan
230 Ross
220 Liam
210 Jay
Any assistance with this would be greatly appreciated!
Many Thanks.

Thanks for all your replies.
What is this single array of custom objects you speak
of? I can't find any reference to it in any of the
text books i'm using.You have a score and a name, right? By custom object, I just meant make your own class:
public class Score implements Comparable
   private int score;
   private String name;
   public Score(String theName, int theScore)
      name = theName;
      score = theScore;
   public String getName() { ... }
   public int getScore() { ... }
   public int compareTo(Object otherScore) { ... }
    // setName, setScore if you need them
}Then make an array:
Score [] scores = new Score[10];Then sort by score using (Arrays is "java.util.Arrays"):
Arrays.sort(scores);If you don't know how many scores you might have, make a List such as ArrayList, add the scores to it, then use "Collections.sort(scores);" instead of "Arrays.sort(scores);".

Similar Messages

  • 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);
    }

  • 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

  • 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;
    }

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

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Can a servlet read a jsp file and display its contents?

    Hi,
    I would like to know if Servlets can read a Jsp file and display its contents.. Right now for our website, I am using a html file to be displayed after a successful post operation through the Servlets...
    -Thanks!

    I posted this in another thread.
    Here's some code that reads using a URL. This doesn't work with JSPs as the server executes JSP when it connects but it's useful for other file types. Note that the filename is a URI</h1>This is <code>show.jsp</code></h1>
    <hr>
    <%! String file = null; %>
    <%! java.io.InputStream is = null; %>
    <%
    file = request.getParameterValues("filename")[0];
    try {
       is = (new java.net.URL(file)).openStream();
    } catch (java.io.IOException ioe) { out.write(file + " not found!<br>"); }
    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line = "";
    %>
    <pre>
    <%
    while((line = in.readLine()) != null) {
    %>
    <%=line%>
    <%
    %>
    </pre>

  • Read a excel file and split its sheets to seperate file ?

    Dear all :
    How to split a excel file into several file, each have one sheet.my code is as below,thanks:
    import org.apache.poi.hssf.usermodel.*;
    import java.io.*;
    import java.util.*;
    import org.apache.poi.poifs.filesystem.*;
    public class Extractxls {
    public static void main(String[] args) throws Exception
    try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    int sheetCount = wb.getNumberOfSheets();
    System.out.println(sheetCount);
    try {
         while(sheetCount > 0) {
         sheetCount--;
         HSSFWorkbook wb1 = new HSSFWorkbook();
         HSSFSheet s = wb1.createSheet();
         String sheetName = wb.getSheetName(sheetCount);
         HSSFSheet sheet = wb.getSheet(sheetName);
    //     HSSFSheet sheet = wb.getSheetAt(sheetCount);
         System.out.println(sheet.toString());
         s = sheet;
    FileOutputStream fileOut = new FileOutputStream("atest" + sheetCount + ".xls");
    wb.write(fileOut);
    fileOut.close();
    } catch (Exception e) {
         System.err.println("Error: " + e.getMessage());
    } catch (Exception e) { e.toString();}

    The HSSFWorkbook class is part of the POI project:
    http://jakarta.apache.org/poi/
    Regards,
    Dave Gilbert
    JFreeChart Project Leader
    I understand poi porject, my problem is that POI can not read a excel file and split its sheets into seperate file (each have one sheet) ?Does any one know how to do it.

  • 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

  • How to read a text file and write text file

    Hello,
    I have a text file A look like this:
    0 0
    0 A B C
    1 B C D
    2 D G G
    10
    1 A R T
    2 T Y U
    3 G H J
    4 T H K
    20
    1 G H J
    2 G H J
    I want to always get rid of last letter and select only the first and last line and save it to another text file B. The output should like this
    0 A B
    2 D G
    1 A R
    4 T H
    1 G H
    2 G H
    I know how to read and write a text file, but how can I select the text when I am reading a text file. Can anyone give me an example?
    Thank you

    If the text file A look like that
    0 0
    0 3479563,41166 6756595,64723 78,31 1,#QNAN
    1 3479515,89803 6756588,20824 77,81 1,#QNAN
    2 3479502,91618 6756582,6984 77,94 1,#QNAN
    3 3479516,16334 6756507,11687 84,94 1,#QNAN
    4 3479519,14188 6756498,54413 85,67 1,#QNAN
    5 3479525,61721 6756493,89255 86,02 1,#QNAN
    6 3479649,5546 6756453,21824 89,57 1,#QNAN
    1 0
    0 3478762,36013 6755006,54907 54,8 1,#QNAN
    1 3478756,19538 6755078,16787 53,63 1,#QNAN
    2 0
    3 0
    N 0
    I want to read the line that before and after 1 0, 2 0, ...N 0 line to arraylist. I have programed the following code
    public ArrayList<String>save2;
    public BufferedWriter bufwriter;
    File writefile;
    String filepath, filecontent, read;
    String readStr = "" ;
    String[]temp = null;
    public String readfile(String path) {
    int i = 0;
    ArrayList<String> save = new ArrayList <String>();
    try {
    filepath = "D:\\thesis\\Material\\data\\CriticalNetwork\\test3.txt";
    File file = new File(filepath);
    FileReader fileread = new FileReader(file);
    BufferedReader bufread = new BufferedReader(fileread);
    this.read = null;
    // read text file and save each line content to arraylist
    while ((read = bufread.readLine()) != null ) {
    save.add(read);
    // split each arraylist[i] element by space and save it to String[]
    for(i=0; i< save.size();i++){
    this.temp = save.get(i).split(" ") ;
    // if String[] contain N 0 such as 0 0, 1 0, 2 0 then save its previous and next line from save arraylist to save2 arraylist
    if (temp.equals(i+"0")){
    this.save2.add(save.get(i));
    System.out.println(save2.get(i));
    } catch (Exception d) {
    System.out.println(d.getMessage());
    return readStr;
    My code has something wrong. It always printout null. Can anyone help me?
    Best Regards,
    Zhang

  • Reading a text file and connecting two server

    Hi,
    I am newbie at java and I have two question ,
    asume you have two server and a client. every server reads its own text file and the client connect both of them and read output data, and counts number of words. you must use socket programming to communicate to servers.
    I need litle code.
    Thanks for your help

    Hi,
    While using ArrayList, use add your elements into it
    as an object subtype if you do not specify ArryList
    certain type.
    But recall that if you use certain
    type(ArrayList<String>,....), you do not add any
    other different type element.What the heck is this all about Merde?

  • Urgent Help:read from text file and write to table

    Hi,
    I'm a super beginner looking for a vi to read this data from a text file and insert it into a table:
       #19
    Date: 05-01-2015
    ID= 12345678
    Sample_Rate= 01:00:00
    Total_Records= 2
    Unit: F
       1 03-23-2015 10:45:46   70.1   3.6
       2 03-23-2015 11:45:46   67.7   2.7
    Output table
    #     date                 time                 x          y        Sample rate    Total Records
    1          03-23-2015     10:45:46        76.8     2.8      01:00:00           2
    2          03-23-2015     10:45:46        48.7     2.1      01:00:00           2
    Thanks for your help in advance.
    Attachments:
    sample.txt ‏1 KB

    jcarmody wrote:
    Will there always be the same number of rows of noise header information?
    Show us how you've read the data and what you've tried to do to parse it.  Once you've got the last rows, you can loop over them using Spreadsheet String to Array (after cleaning up a few messy spaces).
    Jim,
    I didn't know you're that active on here.
    Yes, There will always be the same number of noise header information.
    I'll show you in person
    Regards,

  • Read from text file and seperate column

    hello,
    I have a problem reading my text file. This text file is downloaded from weather link. All data will be changed upon the selection of user. my problem is I can read the data column by column but i cannot retrive the right column header for each data. I also attached the test file. Can somebody help me? Thanks in advance..
    Attachments:
    download.txt ‏8 KB
    read text file.JPG ‏11 KB
    read data.JPG ‏43 KB

    Hi
    Sorry, I missed that one. The file formatting is strange though. It uses spaces to separate columns but also within columns. I attached a modified VI that tries to take care of that, but it fails at the columns "Solar Energy" and "Hi Solar Rad.". This is very difficult to read programmatically as there's one space each between "Solar", "Hi", and "Solar" again. So how do we distinguish between column separator and space within column?
    Is download.txt the original file? Or was it probably modified by an editor that would replace tabs by space characters?
    Attachments:
    test-mod-2.vi ‏11 KB

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

Maybe you are looking for

  • Regarding fetching TIN number of vendor

    Hi all,          from which table i can fetch vendor TIN number Thks Shailesh

  • Conversion or Casting................

    Hi I think i got a superb question.:)Let me explain u first. Widening Conversion::: A conversion that accommodate wider range of values than the original type.e.g., int in=25; double d=in; //is legal because int in is 32 bit and double d is 64 bit. i

  • How to setup AJAX in java platform

    Hi, firstly, i want to say sorry if i post in the wrong forum. I'm using netBeans to develop web application. Does anyone know how can i setup AJAX in my current platform? I can't really get the good example and article on how to setup it. Can anyone

  • Duplicated tunes with iMatch icon

    On one complete CD and a single, all downloaded from the iTunes store recently, duplicate tunes appeared on my iPhone showing the iTunes Match icon. Obviously, my iPhone is displaying both the cloud instance and the 'resident' instance of the tunes.

  • Icon in tree control displayed as @01@ not as a icon symbol

    Hi everybody, I have a field of component TV_IMAGE. During runtime I assigned 'ICON_COMPLETE'. But only @01@ is show in the tree, not the symbol. Does anybody know, what I am doing wrong? Thanks Regards Mario