ReadLine problem

I have a problem in JDeveloper 3.2.3, using Java 1.3.1-02, usin this code:
<Start code>
import java.io.*;
import java.util.*;
public class test {
static DataInputStream kbd = new DataInputStream(System.in) ;
public static void main(String[] args) throws IOException
String temp = "" ;
System.out.println("Simple Java Isql.\n");
System.out.print("Enter something or [ENTER] : ");
System.out.flush();
temp = kbd.readLine();
public test (){
<End code>
This compiles with warning on line 15 (deprecated).
When run it gives:
"F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\jre\bin\javaw.exe" -mx50m -classpath "F:\Program Files\JDeveloper 3.2.3\myclasses;F:\Program Files\JDeveloper 3.2.3\lib\jdev-rt.zip;F:\Program Files\JDeveloper 3.2.3\jdbc\lib\oracle8.1.7\classes12.zip;F:\Program Files\JDeveloper 3.2.3\lib\connectionmanager.zip;F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\lib\dt.jar;F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\jre\lib\rt.jar;F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\jre\lib\i18n.jar" test
Simple Java Isql.
Enter something or [ENTER] : java.io.IOException: The handle is invalid
     at java.io.FileInputStream.readBytes(Native Method)
     at java.io.FileInputStream.read(FileInputStream.java:183)
     at java.io.BufferedInputStream.fill(BufferedInputStream.java:186)
     at java.io.BufferedInputStream.read(BufferedInputStream.java:204)
     at java.io.DataInputStream.readLine(DataInputStream.java:449)
     at test.main(test.java:15)
Exception in thread "main"
If deprecation is handled according manual:
static DataInputStream kbd = new DataInputStream(System.in) ;
replaced with:
static BufferedReader kbd
= new BufferedReader(new InputStreamReader(System.in)) ;
it compiles without error or warning.
Running it shows:
"F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\jre\bin\javaw.exe" -mx50m -classpath "F:\Program Files\JDeveloper 3.2.3\myclasses;F:\Program Files\JDeveloper 3.2.3\lib\jdev-rt.zip;F:\Program Files\JDeveloper 3.2.3\jdbc\lib\oracle8.1.7\classes12.zip;F:\Program Files\JDeveloper 3.2.3\lib\connectionmanager.zip;F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\lib\dt.jar;F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\jre\lib\rt.jar;F:\Program Files\JDeveloper 3.2.3\jdk1.3.1_02\jre\lib\i18n.jar" test
Simple Java Isql.
Enter something or [ENTER] : java.io.IOException: The handle is invalid
     at java.io.FileInputStream.readBytes(Native Method)
     at java.io.FileInputStream.read(FileInputStream.java:183)
     at java.io.BufferedInputStream.read1(BufferedInputStream.java:223)
     at java.io.BufferedInputStream.read(BufferedInputStream.java:280)
     at java.io.FilterInputStream.read(FilterInputStream.java:93)
     at java.io.InputStreamReader.fill(InputStreamReader.java:173)
     at java.io.InputStreamReader.read(InputStreamReader.java:249)
     at java.io.BufferedReader.fill(BufferedReader.java:139)
     at java.io.BufferedReader.readLine(BufferedReader.java:299)
     at java.io.BufferedReader.readLine(BufferedReader.java:362)
     at test.main(test.java:16)
Exception in thread "main"
The same happens using java 1.2.2: (same code):
Exception in thread "main"
"F:\Program Files\JDeveloper 3.2.3\java1.2\jre\bin\javaw.exe" -mx50m -classpath "F:\Program Files\JDeveloper 3.2.3\myclasses;F:\Program Files\JDeveloper 3.2.3\lib\jdev-rt.zip;F:\Program Files\JDeveloper 3.2.3\jdbc\lib\oracle8.1.7\classes12.zip;F:\Program Files\JDeveloper 3.2.3\lib\connectionmanager.zip;F:\Program Files\JDeveloper 3.2.3\java1.2\jre\lib\rt.jar" test
Simple Java Isql.
Enter something or [ENTER] : java.io.IOException: The handle is invalid.
     java.lang.String java.io.BufferedReader.readLine(boolean)
     java.lang.String java.io.BufferedReader.readLine()
     void test.main(java.lang.String[])
Exception in thread main
and in java 1.1.8:
"F:\Program Files\JDeveloper 3.2.3\java\bin\javaw.exe" -mx50m -classpath "F:\Program Files\JDeveloper 3.2.3\myclasses;F:\Program Files\JDeveloper 3.2.3\lib\jdev-rt.zip;F:\Program Files\JDeveloper 3.2.3\jdbc\lib\oracle8.1.7\classes111.zip;F:\Program Files\JDeveloper 3.2.3\lib\connectionmanager.zip;F:\Program Files\JDeveloper 3.2.3\java\lib\classes.zip" test
Simple Java Isql.
Enter something or [ENTER] :
java.io.IOException: read error
     at java.io.FileInputStream.read(FileInputStream.java:158)
     at java.io.BufferedInputStream.read(BufferedInputStream.java:193)
     at java.io.FilterInputStream.read(FilterInputStream.java:101)
     at java.io.InputStreamReader.fill(InputStreamReader.java:158)
     at java.io.InputStreamReader.read(InputStreamReader.java:229)
     at java.io.BufferedReader.fill(BufferedReader.java:136)
     at java.io.BufferedReader.readLine(BufferedReader.java:224)
     at test.main(test.java:16)
Same applies to this (more minimized) code (found elsewhere):
<start code>
import java.io.*;
import java.util.*;
public class test2 {
public static void main(String[] args) throws IOException {
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
          String s=reader.readLine();
     if(s==null) {
               System.out.println("Error: reached end of file!");
               System.exit(1);
          System.out.println("You typed:"+s);
     } catch(IOException e) {
     System.out.println("Could not read line: "+e);
<end code>
Colleagues tried this as well but got the same error.
Using other IDE runs this code without problem.
What can be wrong?

Hey ,
Please avoid to use any proprietary editor if u are using for coding java which facilate coding and execution enviornment also (e.g. JCreator )
Use simple notepad and run it on cosole.
I have tried it 2 ways
with editor it gives same problem as u stated.
and
when used with normal nitepad and console it working okey

Similar Messages

  • Null Pointer and URL parsing

    I am trying to write a Bookmark reader to go through bookmarks on a windows machine and let you know if your booksmarks are old and not valid.
    Anyway, I am getting a nullpointer and having all sorts of problems. My error comes at line 56. (See below, I will point it out)
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Vector;
    * Created by IntelliJ IDEA.
    * User: mlubrano
    * Date: Jan 29, 2003
    * Time: 3:01:20 PM
    * To change this template use Options | File Templates.
    public class LinkMain {
    static String desktopDir = System.getProperty("user.home");
    static String osName = System.getProperty("os.name");
    static String FSEP = System.getProperty("file.separator");
    static String workingDir = new File(System.getProperty("user.dir")).getParent().replace('\\', '/');
    private Vector bookmarkList = new Vector();
    private Vector bookmarkURLs = new Vector();
    public static void main(String[] args) {
    String rootDir = desktopDir + FSEP + "Favorites" + FSEP;
    LinkMain lm = new LinkMain(rootDir);
    //lm.recurseDir(rootDir);
    LinkMain(String root) {
    //LinkHTTPConnect();
    //ReadInBookmarks();
    recurseDir(root);
    ReadInBookmarks();
    //read in boookmarks
    public void ReadInBookmarks() {
    BufferedReader br = null;
    for (int i = 0; i < bookmarkList.size(); i++) {
    try {
    br = new BufferedReader(new FileReader((File)bookmarkList.get(i)));
    while(br.ready()) {
    String line = new String("");
    System.err.println(br.readLine());
    line = br.readLine();
    //Problem is somewhere in here!!!!!!!!!!!!!!!!!!!!!!!!!!!
    if (line.startsWith("URL=")) {
    LinkHTTPConnect(line.substring(4).trim());
    //System.out.println(line.substring(4).trim());
    } catch (FileNotFoundException e) {
    e.printStackTrace(); //To change body of catch statement use Options | File Templates.
    catch (IOException ioe) {
    ioe.printStackTrace();
    public void recurseDir(String startDir) {
    File[] children = new File(startDir).listFiles();
    for (int i = 0; i < children.length; i++) {
    if (children.isDirectory())
    recurseDir(children[i].getAbsolutePath());
    bookmarkList.add(new File(children[i].getAbsolutePath()));
    //System.err.println(children[i].getAbsolutePath());
    //Connect and get results
    public void LinkHTTPConnect(String s) {
    try {
    URL url = new URL(s);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("HEAD");
    conn.connect();
    // GET seems to do a better job of locating it
    if (conn.getResponseCode() != 200) {
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.connect();
    if (conn.getResponseCode() == 200) {
    System.out.println("ok");
    //System.out.println(desktopDir);
    } else
    System.out.println("not found");
    } catch (MalformedURLException e) {
    System.out.println(e);
    } catch (IOException e) {
    System.out.println(e);
    //Print Results in some format

    Oops....
    Well it is not looping right... It seems to be looping the right # of times, but not moving on to the next file...
    The idea is that is looks through your favorites folder and check to make sure that url is valid.. if you run this..
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Vector;
    * Created by IntelliJ IDEA.
    * User: mlubrano
    * Date: Jan 29, 2003
    * Time: 3:01:20 PM
    * To change this template use Options | File Templates.
    public class LinkMain {
      //C:\Documents and Settings\mlubrano
      static String desktopDir = System.getProperty("user.home");
      static String osName = System.getProperty("os.name");
      static String FSEP = System.getProperty("file.separator");
      static String workingDir = new File(System.getProperty("user.dir")).getParent().replace('\\', '/');
      private Vector bookmarkList = new Vector();
      private Vector bookmarkURLs = new Vector();
      public static void main(String[] args) {
        String rootDir = desktopDir + FSEP + "Favorites" + FSEP;
        LinkMain lm = new LinkMain(rootDir);
        //lm.recurseDir(rootDir);
      LinkMain(String root) {
        //LinkHTTPConnect();
        //ReadInBookmarks();
        recurseDir(root);
        ReadInBookmarks();
      //read in boookmarks
      public void ReadInBookmarks() {
        BufferedReader br = null;
        for (int i = 0; i < bookmarkList.size(); i++) {
          try {
            br = new BufferedReader(new FileReader((File) bookmarkList.get(i)));
            while (br.ready()) {
              String line = new String("");
              System.err.println(br.readLine());
              line = br.readLine();
              while (line != null) {
                if (line.startsWith("URL=") && line != null) {
                  LinkHTTPConnect(line.substring(4).trim());
                  System.out.println(line.substring(4).trim());
          } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use Options | File Templates.
          } catch (IOException ioe) {
            ioe.printStackTrace();
      public void recurseDir(String startDir) {
        File[] children = new File(startDir).listFiles();
        for (int i = 0; i < children.length; i++) {
          if (children.isDirectory())
    recurseDir(children[i].getAbsolutePath());
    bookmarkList.add(new File(children[i].getAbsolutePath()));
    //System.err.println(children[i].getAbsolutePath());
    //Connect and get results
    public void LinkHTTPConnect(String s) {
    try {
    URL url = new URL(s);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("HEAD");
    conn.connect();
    // GET seems to do a better job of locating it
    if (conn.getResponseCode() != 200) {
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.connect();
    if (conn.getResponseCode() == 200) {
    System.out.println("ok");
    //System.out.println(desktopDir);
    } else
    System.out.println("not found");
    } catch (MalformedURLException e) {
    System.out.println(e);
    } catch (IOException e) {
    System.out.println(e);
    //Print Results in some format
    It loops through the first file it finds x number of times (x being the total number of files you have)
    Thx,
    Usul

  • KDE: Cannot upgrade... whassup?

    Hi!
    When I try to upgrade Arch Linux with pacman -Suy , it downloads everything but then I get lots of error messages and nothing works! What's up? I heard also about missing dependencies, like upgrading readline will not upgrade bash and the system gets broken... hmmmm...
    can I upgrade savely?
    I get masses of such error messages:
    kdebase-konqueror: /usr/share/apps/konqueror/about/plugins.html exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/about/plugins_rtl.html exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/about/specs.html exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/about/tips.html exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/about/top-left-konqueror.png exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/konqueror.rc exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/pics/indicator_connect.png exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/pics/indicator_empty.png exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/pics/indicator_noconnect.png exists in filesystem
    kdebase-konqueror: /usr/share/apps/konqueror/pics/indicator_viewactive.png exists in filesystem
    many thanks for any tips...

    something like:
    pacman -Qo /usr/share/apps/konqueror/pics/indicator_noconnect.png
    /usr/share/apps/konqueror/pics/indicator_noconnect.png is owned by kdebase 4.2.4-1
    ah..., is it because I did a restore of an older backup? The newer KDE files were not deleted and now they cause trouble?
    this readline problem (I just upgraded CUPS what upgraded readline) broke my KDE and I had to restore.
    maybe I can force an override? ... have to check the pacman manual...

  • Problem with input.readLine()

    import java.io.*;
    public class HorseMain
         public static void main(String[] args) throws IOException
              //declare the FILENAME
              //the user will later give the FILENAME
              String horseFILENAME;
              //declare the variables to be manipulated
              String name, stable, winner, commentsStewards, commentsJockey, commentsPersonal;
              int rating, race, distance;
              String command;
              //Mastery Factor 9: Parsing a text file or other data stream
              //This will be used to accept the input from the user
              BufferedReader input = new BufferedReader( new InputStreamReader(System.in) );
              System.out.println("\t\t\t\tHORSES");
              System.out.println("Enter the name of the file where the horses are saved:");
              horseFILENAME = input.readLine();
              //calling the HorseFile class
              //the actual argument horseFILENAME will be used to open the file
              HorseFile horse = new HorseFile(horseFILENAME);
              //call the load method to load the contents of the file storing the data
              horse.load();
              //asking for user input
              System.out.println("Please enter one of the given commands");
              System.out.println("\t[a]dd a horse");
              System.out.println("\t[d]elete a horse");
              System.out.println("\t[e]dit details of a horse");
              System.out.println("\t[s]earch for a horse by its name");
              System.out.println("\t[p]rint the details of all the horses in the collection");
              System.out.println("\t[g]et the horses having encountered problems in their last race");
              System.out.println("\t[q]uit the program");
              while (true)     //the system must return true
                   System.out.println("Command: ");
                   command = input.readLine();
                   //using simple if...else selection to determine what action to be taken from command
                   //if the user wants to add a horse
                   if (command.equals("a"))
                        obtainName(name);
                        //perform search to determine whether this horse already exists
                        //if the horse already exists, message to inform user
                        if (horse.search(name) != null)
                             //message to inform the user that this horse already exists
                             System.out.println(name+ " already exists!");
                        else
                             //obtain the details on the horse
                             obtainStable(stable);
                             obtainRating(rating);
                             obtainRace(race);
                             obtainDistance(distance);
                             obtainWinner(winner);
                             obtainCommentsStewards(commentsStewards);
                             obtainCommentsJockey(commentsJockey);
                             obtainCommentsPersonal(commentsPersonal);
                             //add a new horse record
                             if (!horse.add(name, stable, rating, race, distance, winner, commentsStewards, commentsJockey, commentsPersonal))
                                  System.out.println("Sorry");
                                  System.out.println(name + " cannot be written to file");
                   //if the user wants to delete a horse
                   if (command.equals("d"))
                        System.out.println("Enter name of horse to be deleted: ");
                        name = input.readLine();
                        //perform search to determine whether this horse already exists
                        //if horse does exist, horse is deleted
                        if (horse.search(name) != null)
                             horse.delete(name);
                             System.out.println(name + " deleted!");
                        //if horse does not exist, message is output
                        else
                             System.out.println(name + " not found!");
                   //if the user wants to edit the details of a horse
                   if (command.equals("e"))
                        System.out.println("Enter name of horse to be edited: ");
                        name = input.readLine();
                        //perform search to determine whether this horse already exists
                        //if the horse does exist
                        if (horse.search(name) != null)
                             //obtain the new details of the horse
                             obtainStable(stable);
                             obtainRating(rating);
                             obtainRace(race);
                             obtainDistance(distance);
                             obtainWinner(winner);
                             obtainCommentsStewards(commentsStewards);
                             obtainCommentsJockey(commentsJockey);
                             obtainCommentsPersonal(commentsPersonal);
                             horse.edit(name, stable, rating, race, distance, winner, commentsStewards, commentsJockey, commentsPersonal);
                        //if the horse does not exist
                        else
                             System.out.println(name + "not found in collection");
                   //if the user wants to print the details of all the horses
                   if (command.equals("p"))
                        horse.display();
                   //if the user wants to quit the program
                   if (command.equals("q"))
                        break;     //the system exits from the if...else selection
              input.close();
              horse.save();
         /**This is the method to get the name of a horse from the user
         **validation rules: length check
         **The length of a horse name cannot exceed 18 characters.
         public static void obtainName(String name)
              System.out.println("Name of horse: ");
              name = input.readLine();
              //using simple if...else to validate user input
              if (name.length() <= 18)
                   //do nothing
              else
                   //output error message
                   System.out.println("Error! Name should not exceed 18 characters");
                   //Using mastery factor recursion to allow the user to input the name again
                   obtainName(name);
         /**This is the method to get the stable of a horse from the user
         **No validation rules are used
         **Any string is accepted
         public static void obtainStable(String stable)
              System.out.println("Stable: ");
              stable = input.readLine();
         /**This is the method to get the rating of the horse from the user
         **Validation rules: range check
         **Rating should be between 20 and 110
         public static void obtainRating(int rating)
              System.out.println("Rating: ");
              rating = Integer.parseInt(input.readLine());
              //using multiple if...else selection
              if ( (rating >= 20) && (rating <= 110) )
                   //do nothing
              else
                   //output error message
                   System.out.println("Error! Rating should be between 20 and 110");
                   //using mastery factor - recursion - to allow the user to input the rating again
                   obtainRating(rating);
         /**This is the method to get the number of the last race run by the horse
         **Validation rules: range check
         **Race number should be between 11 and 308
         public static void obtainRace(int race)
              System.out.println("Race number: ");
              race = Integer.parseInt(input.readLine());
              //using if...else
              if ( (race >= 11) && (race <= 308) )
                   //do nothing
              else
                   //output error message
                   System.out.println("Error! Race number should 11 and 308");
                   //using mastery factor - recursion - to allow the user to input the rating again
                   obtainRace(race);
         /**This is the method to get the distance of the last race
         **Validation rule: comparison check
         **Distance can either be 1365, 1400, 1500, 1600, 1800, 2000, 2200, 2400
         public static void obtainDistance(int distance)
              System.out.println("Distance: ");
              distance = Integer.parseInt(input.readLine());
              //using if...else
              if ( (distance == 1365) || (distance == 1400) || (distance == 1500) || (distance == 1600) || (distance == 1800) || (distance == 2000) || (distance == 2200) || (distance == 2400) )
                   //do nothing
              else
                   //output error message
                   System.out.println("Error! Distance can either 1365, 1400, 1500, 1600, 1800, 2000, 2200, 2400");
                   //using mastery factor recursion to allow the user to input the distance again
                   obtainDistance(distance);
         /**This is the method to get the winner of the last race
         **Validation rule: length check
         **The name of the winner cannot exceed 18 characters
         public static void obtainWinner(String winner)
              System.out.println("Winner: ");
              winner = input.readLine();
              //using if...else
              if (winner.length() <= 18)
                   //do nothing
              else
                   //output error message
                   System.out.println("Error! The name of the winner cannot exceed 18 characters");
                   //using mastery factor recursion to allow the user to input the winner again
                   obtainWinner(winner);
         /**This is the method to get the stewards' comments on a horse
         **No validation rules
         **Any string is accepted
         public static void obtainCommentsStewards(String commentsStewards)
              System.out.println("Stewards' comments: ");
              commentsStewards = input.readLine();
         /**This is the method to get the stewards' comments on a horse
         **No validation rules
         **Any string is accepted
         public static void obtainCommentsJockey(String commentsJockey)
              System.out.println("Jockey's comments: ");
              commentsJockey = input.readLine();
         /**This is the method to get the stewards' comments on a horse
         **No validation rules
         **Any string is accepted
         public static void obtainCommentsPersonal(String commentsPersonal)
              System.out.println("Personal comments: ");
              commentsPersonal = input.readLine();
    }

    I see one problem already though. You defined "input" as a local variable in your main method, and then refer to it all over the place, outside of the main method.
    If you want to use input like that, you'll have to define it as a field, not a local variable.
    By the way your code is structured in a kind of hairy way. In OOP you usually want to structure your code around self-contained, encapsulated state and behavior, not just as a bunch of individual actions effecting global variables.

  • Problems with readLine()

    I am using readLine() to read a file into an array, and when i print the line there are now "?" characters in place of some of the spaces(not all of them). i tried using string.replaceAll("\\?"," ") to fix the problem but it seems that the ? in the line is not actually a question mark character, as the regex does not "see" it at all. I also need to search the array for certain words, and at this point even putting the "?" in comes up without a match:
    if("Simple\\?test".equals(string))
    return i;
    I will post the rest of the code and system output if that explanation wasn't clear enough. Thanks in advance.

    Most likely the information is encoded in a manner that is not compatible with the default that your computer uses for display, and non-displayable characters are being replaced with the question mark.
    Check how the data is encoded, and set your program and computer for compatibility.
    For diagnosis, consider printing the information in hexidecimal format.

  • BufferedReader's readLine() method problem (REPOST)

    Hello,
    If anyone can help me out I would not have to struggle :)
    Here is the thing. I have a file like this:
    1 srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniui yjpeppaezftgjfviwxunu
    2 ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohe njixwufcdlbjlkoqevqdy
    3 stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzg iefgarenbxnxtxnqdqpfh
    4 dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifph tldawxsfepotkgqqsivur
    5 fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycr xdhnhxyitkeqynedrbroh
    6 hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyz apcinhjyysxsdwfjugndr
    7 pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfid xyoktwupsuqbqgnxdfbze
    8 avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpku uttidlnqftdnzqpqafels
    9 oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbn bnrflotpqytqzbgnkeyrk
    10 unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofb xfsynlxhyuvqprqbvoruk
    and my java programs is like this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    while((bufferedReaderObject.readLine()) != null)
    System.out.println(bufferedReaderObject.readLine());
    Last System.out.println statement only displays second, forth, sixth, eigth, tenth and null lines. Why not every line? Any ideas? Thanks!
    Re: BufferedReader's readLine() method problem.
    Author: EagleEye101 Feb 18, 2005 8:48 PM (reply 1 of 1)
    You do relize that when you call the in.readLine() in your loop conditional and in your loop body it reads in diffrent lines. Try this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    String s = bufferedReaderObject.readLine();
    while(s != null)
    System.out.println(bufferedReaderObject.readLine());
    s = bufferedReaderObject.readLine();
    Every time you call the readLine method, it does read a diffrent line. Java does not know you want to read the same line twice.
    Tried it, did not work. I need to go through each line of the file I have. Any ideas?

    solution should be in your other thread.
    Please do not repeat threads--it really bugs the people here, just some 'nettiquite' --I don't mean to be a grouch.
    --later.  : )                                                                                                                                                                                                                                                                                                                                                       

  • BufferedReader's readLine() method problem.

    Hello,
    If anyone can help me out I would not have to struggle :)
    Here is the thing. I have a file like this:
    1     srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniuiyjpeppaezftgjfviwxunu
    2     ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohenjixwufcdlbjlkoqevqdy
    3     stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzgiefgarenbxnxtxnqdqpfh
    4     dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifphtldawxsfepotkgqqsivur
    5     fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycrxdhnhxyitkeqynedrbroh
    6     hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyzapcinhjyysxsdwfjugndr
    7     pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfidxyoktwupsuqbqgnxdfbze
    8     avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpkuuttidlnqftdnzqpqafels
    9     oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbnbnrflotpqytqzbgnkeyrk
    10     unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofbxfsynlxhyuvqprqbvoruk
    and my java programs is like this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    while((bufferedReaderObject.readLine()) != null)
    System.out.println(bufferedReaderObject.readLine());
    Last System.out.println statement only displays second, forth, sixth, eigth, tenth and null lines. Why not every line? Any ideas? Thanks!

    You do relize that when you call the in.readLine()in
    your loop conditional and in your loop body itreads
    in diffrent lines. Try this:
    public String searchForAString(String fileName,int
    lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new
    FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject =new
    BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new
    DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new
    BufferedReader(new
    InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    String s = bufferedReaderObject.readLine();
    while(s != null)
    System.out.println(bufferedReaderObject.readLine());
    s = bufferedReaderObject.readLine();
    Every time you call the readLine method, it doesread
    a diffrent line. Java does not know you want toread
    the same line twice.Err, shouldn't that be:
    while(s != null)
    System.out.println(s);
    s = bufferedReaderObject.readLine();
    Otherwise, you're still discarding a line if you use
    two readLines in the while loop.yes you are correct... srry late last night and I wsa copying his code :).

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

  • Problems with String.split(regex)

    Hi! I'm reading from a text file. I do it like this: i read lines in a loop, then I split each line into words, and in a for loop I process ale words. Heres the code:
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line;
    while ((line = reader.readLine()) != null) {
        String[] tokens = line.split(delimiters);
        for (String key : tokens) {
    doSthToToken();
    reader.close();The problem is that if it reads an empty line, such as where is only an "\n", the tokens table has the length == 1, and it processes a string == "". I think the problem is that my regex delimiters is wrong:
    String delimiters = "\\p{Space}|\\p{Punct}";
    Could anybody tell me what to do?

    Ok, so what do you suggest?I suggest you don't worry about it.
    Or if you are worried then you need to test the two different solutions and do some timings yourself.
    And how do you know the regex lib is so slow and badly written?First of all slowness is all relative. If something takes 1 millisecond vs 4 milliseconds is the user going to notice? Of course not which is why you are wasting your time trying to optimize an equals() method.
    A general rule is that any code that is written to be extremely flexible will also be slower than any code that is written for a specific function. Regex are used for complex pattern matching. StringTokenizer was written specifically to split a string based on given delimiters. I must admit I haven't tested both in your exact scenario, but I have tested it in other simple scenarios which is where I got my number.
    By the way I was able to write my own "SimpleTokenizer" which was about 30% faster than the StringTokenizer because I was able to make some assumptions. For example I only allowed a single delimiter to be specified vs multiple delimiter handled by the StringTokenizer. Therefore my code could be very specific and efficient. Now think about the code for a complex Regex and how general it must be.

  • Problems with string tokenizer

    okay heres my problem, i have a textarea displaying a program listing and i have to extract variables i.e public int something;
    i have tried many different approaches but still the output is not what i was looking for. Can someone have a look at my code and check for mistakes that i cant find
    public void createDataDictionary() {
              if(fullText.equals("")) return;//do nothing if no text exists
              String checkText = fileContents.getText();//store text area contents into string
              String dataType = "";
              String variable = "";
              String accessModifier = "";
              StringTokenizer str = new StringTokenizer(checkText," \n", true);
              fileCheckBox.setText("");//clear file check box
              while(str.hasMoreTokens()) {//loop while there are more tokens to tokenize
                   try{                    
                        checkText = str.nextToken();
                        //check for comments
                        if((checkText.startsWith("//")) || (checkText.equals("//")) ||
                           (checkText.startsWith("/**")) || (checkText.equals("/**")) ||
                           (checkText.startsWith("*")) || (checkText.equals("*"))) {
                             isComment = true;                    
                        if((checkText.equals("\n"))) isComment = false;
                        if(!isComment)
                             //check for access modifiers
                             if((checkText.equals("public")) || (checkText.equals("private")) ||
                                (checkText.equals("protected"))) {
                                          accessModifier = checkText;
                                     }else {
                                          accessModifier = "";
                             //check for data types             
                             if((checkText.equals("boolean")) || (checkText.equals("char")) ||
                                     (checkText.startsWith("String")) || (checkText.equals("int"))) {
                                       dataType = checkText;
                                       variable = str.nextToken();//get variable expression
                                       System.out.println(accessModifier + " " + dataType + " " + variable);
                   }catch(NoSuchElementException nsee) {//not enough tokens to complete operation
                        JOptionPane.showMessageDialog(null, "End of file");
                        return;//break from method
         }here is sample text
    private String seven = "help";
    char five[];
    // String here
    //int found
    public boolean okay
    and here is the output
    String
    char
    String
    boolean
    //note the space before each output
    hope someone can help
    thanx in advance

    1. Why do you check to see if the token starts with
    //, /*, etc, etc. Later you check if the token
    equals private, public, protected. It couldn't
    equal if it started with a comment.if the token starts with a comment i dont want to read the rest of the line, so i set the isComment flag to true
    2. I strongly suggest that you do it line by line.
    Perhaps a string tokenizer that only tokenizes by
    lines, then within that loop, another that tokenizes
    by whitespace. i take it you mean putting the text into a bufferedreader and then using readLine()?? Bit new to string tokenization as you can possibly see
    i managed to get the small test text to work more or less as i wanted but when ever i load a large code listing, the results are erratic to say the least
    heres a section of this code
    private int textNum = 0;/**Integer used to hold the text position within any given line*/
         private int lineNum = 0;/**Integer used to hold the line number within any given file*/
         static boolean application = false;/**Used to track if applet is ran from a browser or JAR file*/
         static boolean fileOpened = false;/**Used to track if file has already been opened*/
         static boolean isComment = false;
         private char lCurve = '(';
         private char rCurve = ')';
         private char lCurly = '{';
         private char rCurly = '}';
         private char lSquare = '[';
         private char rSquare = ']';
         String fullText = "";and heres the output
    public int textNum //should be private!!!!
    int lineNum //missing private
    boolean application //missing static
    boolean fileOpened //missing static
    boolean isComment //missing static
    //all below missing private     
    char lCurve
    char rCurve
    char lCurly
    char rCurly
    char lSquare
    char rSquare
    String fullText //not there at all

  • Arraylist.add() problem

    Hi,
    I'm trying to read a CSV text file into an arraylist.
    I can read the text file fine, its just when it gets to the actual arraylist.add() part it just .. .. doesn't work. It can print the values from the CSV file no problem. I'm sure my syntax is fine, everything compiles. I've read it and double checked it and checked it again.
    It just doesn't work .. I don't know why.
    The arraylist I am trying to read into is
    ArrayList<Customer> customers = new ArrayList<Customer>();Within other parts of the program I can read in dummy data, eg
    customers.add(new Customer(01, "Jims Mowing", "16 Long Grass Street", "Thorndale", "123-4567", "[email protected]"));
    but suffice to say, yes, it is kaput.
       * READING THE CUSTOMER TEXT FILE INTO THE ARRAY LIST
      private void custFileToArray ()
        RectangleTUI results = new RectangleTUI(); // create results object
        try   
          BufferedReader inputStream = new BufferedReader(new FileReader(PATHNAME + CUSTFILE));
          System.out.println("Contents of file: " + CUSTFILE); // print heading
          String line = inputStream.readLine(); // read first line
          while (line !=null) // test for end of file (EOF)
            results.loadCustFile(line);       
            line = inputStream.readLine(); // read next line
          // close file
          inputStream.close();
        // catch any file open errors
        catch(FileNotFoundException e)
          System.out.println("Error opening file: " + CUSTFILE);
          System.exit(0);
        catch(NoSuchElementException e)
          System.out.println("ATTENTION: One or more " + CUSTFILE + " records are missing data");
        // catch any file reading errors
        catch(IOException e)
          System.out.println("Error reading from file: " + CUSTFILE);
          System.exit(0);
        System.out.println("File Reading Complete");  
      private void loadCustFile(String textLine)
        String delimiters = ","; // set tokenizer delimiter
        StringTokenizer RecordFields = new StringTokenizer(textLine,delimiters);  
        int cidNum = Integer.parseInt(RecordFields.nextToken()); // Customer ID
        System.out.println(cidNum + " Hello I am a stupid piece of code. I don't like to work properly");
        String cName = RecordFields.nextToken();   // Name
        String cAdd = RecordFields.nextToken();   // Street Address
        String cBurb = RecordFields.nextToken();   // Suburb
        String cPhone = RecordFields.nextToken();   // Phone
        String cEmail = RecordFields.nextToken();   // Email
        customers.add(new Customer(cidNum, cName, cAdd, cBurb, cPhone, cEmail));
      }

    Cowzor wrote:
    Hi,
    Cheers for the replies & the printStackTrace tip.
    The thing is it's not actually throwing up any errors or crashing. It's acting as if everything is AOK - but since it then says there's nothig in the arraylist there must be a problem ... somewhere.
    Sorry if I've mis-understood what you were saying
    Here's the dummy data I'm using just incase it's at all relevant
    200701,Jims Mowing,16 Long Grass Street,Thorndale,123-4567,[email protected]
    200702,Chevy Racers,2 Raceway Drive,Boganville,123-4567,[email protected]
    200703,Renta Dent,82 Airport Oaks Road,Airport Oaks,123-4567,[email protected]
    200704,Discount Taxis,8 Poor Place,Otara,123-4567,[email protected]
    u split contains of CSV file on basis of , (comma) and read it

  • Problem with ArrayList

    Hello,
    I am having a problem with a program I am trying to write. The idea of the program is to:
    A) read a list of movies list from a text file
    B) create an object for each movie using the information from the text file
    C) place the objects into an arrayList
    My problem is that when I check my arrayList it seems to only contain multiple copies of the first movie read from the text file. Here is my code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    public class MovieReader
         PrintWriter outputStream = null;
         public void readFile()
              try
                      BufferedReader in = new BufferedReader(new FileReader("movie.txt"));
                      String str;
                      while ((str = in.readLine()) != null)
                           process(str);
                      in.close();
              catch (IOException e)
                  e.printStackTrace();
         ArrayList <ValidMovie> movieList = new ArrayList<ValidMovie>();
         private void process(String line)
              String[] array = line.split("\t");
              int i = 0;
              for ( i = 0; i < array.length; i++)
                   String tempTitle = array[0];
                   String tempYear = array [1];
                   String tempRating = array [2];
                   String tempFormat = array [3];
                   ValidMovie uuj = new ValidMovie(tempTitle, tempYear, tempRating, tempFormat);
                   movieList.add(uuj);
              System.out.println("item at index 1 is:   " + movieList.get(1));
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         private void writeFile(String [] arrayL)
              String [] arrayWrite = arrayL;
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
         public static void main(String[] args)
              MovieReader mv = new MovieReader();
              mv.readFile();
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    }This is the code that creates an object for each movie:
    import java.io.Serializable;
    public class ValidMovie implements Serializable
         private String title;
         private String year;
         private String rating;
         private String format;
         public ValidMovie()
         public ValidMovie(String tTitle, String tYear, String tRating, String tFormat)
              title = tTitle;
              year = tYear;
              rating = tRating;
              format = tFormat;
         //Getters for title, year, rating and format
         public String getTitle ()
              return title;
         public String getYear ()
              return year;
         public String getRating ()
              return rating;
         public String getFormat ()
              return format;
         public String toString ()
              return title + "\t" + year + "\t" + rating + "\t" + format;
    }The following is what I have in the movie.txt file:
    Bamboozled     2000     2     DVD
    What Lies Beneath     2000     1.5     DVD
    Beneath the Planet of the Apes     1970     1     DVD
    You Can Count On Me     2000     3.5     Theater
    And finally this is the result when I run the code:
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    I am sure that it is something simple that I am overlooking but I cannot figure it out. When I change the index in the code:
    System.out.println("item at index 1 is:   " + movieList.get(1));to 0 or 2 or 3 then result is the same, it will just show the first movie in the text file. Any help would be greatly appreciated. Thanks

    Thanks for the reply, it helped but I am now getting 4 of each of the movies after adding you suggestion. This is much better now I just need to figure out why the loop is causing the extra copies. Thanks again :)
    Item 0: Bamboozled     2000     2     DVD
    Item 1: Bamboozled     2000     2     DVD
    Item 2: Bamboozled     2000     2     DVD
    Item 3: Bamboozled     2000     2     DVD
    Item 4: What Lies Beneath     2000     1.5     DVD
    Item 5: What Lies Beneath     2000     1.5     DVD
    Item 6: What Lies Beneath     2000     1.5     DVD
    Item 7: What Lies Beneath     2000     1.5     DVD
    Item 8: Beneath the Planet of the Apes     1970     1     DVD
    Item 9: Beneath the Planet of the Apes     1970     1     DVD
    Item 10: Beneath the Planet of the Apes     1970     1     DVD
    Item 11: Beneath the Planet of the Apes     1970     1     DVD
    Item 12: You Can Count On Me     2000     3.5     Theater
    Item 13: You Can Count On Me     2000     3.5     Theater
    Item 14: You Can Count On Me     2000     3.5     Theater
    Item 15: You Can Count On Me     2000     3.5     Theater

  • Reading into ArrayList problem - what is wrong?

    Hi, I am trying to read a list of strings into an ArrayList and am having some problems. I have created a main() which at the moment does nothing, its just to make sure that the array's content is genuine (meaning consistent with the string in the text file) so I am having it simply printed out to screen. The error I am getting is "cannot resolve symbol, variable array" by my compiler (Jcreator). I will paste the code below:
    import java.io.*;
    import java.util.*;
    public class hostList{
    public hostList()
    try
    File input = new File("hosts.txt");
    BufferedReader in=new BufferedReader(
         new InputStreamReader(new FileInputStream(input)));
         ArrayList list=new ArrayList();
         String line;
         while((line=in.readLine())!=null)
              list.add(line);
         String[] array=new String[list.size()];
         list.toArray(array);
         in.close();
    catch(FileNotFoundException e)
    System.err.println("File not found...");
    catch(IOException e)
    System.err.println("IO Problem");
    }//hostLst()
         public static void main (String [] args){
              System.out.println("Array content:");
              System.out.println("array " + array[0]);
              for (int i=0; array[i] !=null; i++)
                   System.out.println(array);
         }//main
    }//class
    Also, how would I use the array objects in another class, say class B. How can I access the arrays in class B so that i can use its methods? eg. array[i].doSomething(); where doSomething() is a method in class B. What libraries would i need to import (if any) ?
    Help is appreciated, thanks.

    this code wont compile bcas in main method u r not creating the object of this class also the var array is not globally declared hence wont be accesibile outside
    u can try this modified code
    import java.io.*;
    import java.util.*;
    public class hostList{
    String[] array=null;
    public hostList()
    try
    File input = new File("hosts.txt");
    BufferedReader in=new BufferedReader(
    new InputStreamReader(new FileInputStream(input)));
    ArrayList list=new ArrayList();
    String line;
    while((line=in.readLine())!=null)
    list.add(line);
    array=new String[list.size()];
    list.toArray(array);
    in.close();
    catch(FileNotFoundException e)
    System.err.println("File not found...");
    catch(IOException e)
    System.err.println("IO Problem");
    }//hostLst()
    public static void main (String [] args){
    hostList h=new hostList();
    System.out.println("Array content:");
    System.out.println("array " + h.array[0]);
    }//main
    }//class

  • Problem appending multiple lines with StringBuffer()

    I have problem executing this code -
    I am reading a line from keyboard. And after every line I store a space as well.
    O/p shows just the first line, space and then null.
    Why would it not print the next lines.
        StringBuffer buf = new StringBuffer();
    do {
    str = br.readLine();
        buf.append(str).append(" ");
       } while (str != null);

    Well, when I input 3 lines and press ^C to end the
    input , the above lines get appended but the last
    line does not append.Why are you pressing ^C? That should make your app abend if you're reading from the System.in stream.
    Anyway, I'd guess you're entering the last line without pressing Enter, so it doesn't actually get entered (nor read).

  • Connection Problem while client is behind proxy and server out side proxy

    hello
    i implemented ChatApplication in JAVA, for that i used socket connection when client and server both are in same network then it's working fine.
    but when my server is on internate and client is behind proxy and try to connect with server
    it not able to connect i get exception.
    i serch most of forum i got same answer and i try it but i was not success.
    any kind of help is appriciated.
    i attached my code(which i implement for testing ) pls reply me
    thanks in advance.
    Server.java
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    class Server {
       public static void main(String args[]) {
          String data = "you are successfully connected with server.";
          try {
             ServerSocket srvs = new ServerSocket(1234);
             Socket skt = srvs.accept();
             System.out.print("Server has connected!\n");
             PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
             System.out.print("Sending string: '" + data + "\n");
             out.print(data);
             out.close();
             skt.close();
             srvs.close();
          catch(Exception e) {
             System.out.print("Whoops! It didn't work!\n");
    ProxyClient.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class ProxyClient{
       public static void main(String args[]) {
         String host="61.17.212.29";
         int port=1234;
               String line;
         Properties properties = System.getProperties();
         /*properties.put("firewallSet", "true");
         properties.put("firewallHost", "192.168.0.1");
         properties.put("firewallPort", "808");*/
         properties.put("socksProxySet","true");
         properties.put("socksProxyHost", "192.168.0.1");
         properties.put("socksProxyPort", "1080");
         System.setProperties (properties);
         try {
         /*SocketAddress addr = new InetSocketAddress("192.168.0.1", 1080);
         Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
         Socket skt = new Socket(proxy);
         InetSocketAddress dest = new InetSocketAddress("61.17.212.29",1234);
         skt.connect(dest);*/
             System.out.println("before socket taken");
             Socket skt = new Socket(host,port);
             System.out.println("after socket taken");
             BufferedReader networkBin = new BufferedReader(new InputStreamReader(skt.getInputStream()));
             System.out.println("Received string: '");
             line = networkBin.readLine();     // Read one line
          while(true)
                 System.out.println(line);     // Output the line
                 line = networkBin.readLine(); // Read the next line, if any
          catch(Exception e) {
             System.out.print("Whoops! It didn't work!\n");
         e.printStackTrace();
    }

    Now look here. I could not care less about this
    code. I don't know anything about it, I don't
    want to know, I have already recommended you don't
    use it, and I have also given you a simpler and
    better solution. If you don't want to take my advice
    that is your privilege and your problem.ya i has understand system propertis i have setted and u can see it in the code i have tried by both system properties and also J2SE 5.0 proxy class but i got a same problem malformed Exception server refuse to connection.
    is there any problem at sever side?
    can u tell me in which way u r teling to set the propery i m looking forward for ur reply.
    ya i m sure u will give me.................reply "ejp".
    Thnx in advance.

Maybe you are looking for

  • Upgrade mac os 10.5.6 without disk

    How can I upgrade mac os 10.5.8 to 10.6 over the internet.

  • Activity confirmation issue

    Dear Gurus, We are facing issue in confirmation of Activity such as power , steam. As in process industry output is variable. accordingly at the time of confirmation activity viz power , steam should varies is it possible? In transaction cor6 we can

  • Smartform Print Problem

    Hi all, Am taking printout of a Purchase order. <i><u>The form contains only a single page and is preprinted form with a custom page format</u></i>. I also have a couple of other windows to be printed at the end of main page. Am taking print in one o

  • Open with:

    I have installed the new Office 2008 but I want to use Excel 2004 as my default spreadsheet program. If I go to Get Info on an .xls file and change the Open with: to Excel 2004 (which actually shows up as Excel O70724) and click Change All..., I get

  • Shortcut for switching Tabs

    There used to be a shortcut in Safari for moving between tabs. I don't see that anymore. Seems like the only way to do it is to click the tab you want. Is that right?