Need help reading a file ~!

Hi,
I cant seem to read this file. It compiles without errors, but i get a java.nullPointerException when i run it. My data file looks like this:
5
class1
class2
class3
class4
class5
1-2 1-3 2-4 3-4 4-5
here is my code to read the file:         public void Read(String fileName) {
                try {
                        String num; //number of cells
                        String cells; //cell data
                        FileReader file = new FileReader(fileName);
                        BufferedReader in = new BufferedReader (file);
                        num = in.readLine();
                        number = Integer.valueOf(num).intValue(); //converts string to int
                        co = new ClassObject[number];
                        System.out.println("There are " + number + " total classes");
//## PROBLEM OCCURS IN THIS FOR LOOP which reads in the 5 names of classes
                        for (int b=0; b<number; b++){
                               co.className = in.readLine();
} //#### end of problem
while ((cells = in.readLine()) != null) {
StringTokenizer st1 = new StringTokenizer(cells, " ");
while (st1.hasMoreTokens()) {
String ST1 = st1.nextToken();
StringTokenizer st2 = new StringTokenizer(ST1, "-");
String ST2 = st2.nextToken();
co[x] = new ClassObject();
co[x].classNumber = Integer.valueOf(ST2).intValue();
ST2 = st2.nextToken();
co[x].classRelation = Integer.valueOf(ST2).intValue();
x++;
} catch (IOException e) {
System.out.println("Warning: Cannot Read File");
System.exit(0);
setPositions();
thanks for any help!

Sorry, I didn't notice your comment in the code.
for (int b=0; b<number; b++){
  co[ b]= new ClassObject();
  co[ b].className = in.readLine();
}

Similar Messages

  • Need help reading raw files!

    Help please!  Cannot read raw files of my Nikon D5000.  Have downloaded Camera Raw 5.3 and followed instruvctions.  5.3 supports the D90 which is supposedly essential the same.  Any suggestions?

    Read the posts in the following link:-
    http://www.elementsvillage.com/forums/showthread.php?p=463255#post463255
    Try the DNG converter or the DPP software supplied with your camera until ACR 5.4 is finalized, as suggested in the posts.
    I have read that there is a way to get the Release Candidate 5.4 installed in PSE 6/7 but you need some skills in understanding computer files.

  • Need help, reading next file line

    i have a file that i am reading using this code, this code reads only string on the first line
    i wnat it to read the second line from the file when the method is called again
    private transactionLine="";
    public void fileReading()
    try
              try
                   FileInputStream finstr = new FileInputStream(userFile);          
              BufferedInputStream bfinstr = new BufferedInputStream(finstr);
              DataInputStream dainsstr = new DataInputStream(bfinstr);
                             transactionLine = dainsstr.readLine();     //holds the transaction line
                             System.out.println(transactionLine);
              catch(FileNotFoundException fnf)
                   System.out.println("File not found");
                   userFile=userInput();
                   fileReading();
                   catch(IOException ioe)
                        System.out.println("io exception at point 1");//point 1

    How big is your file ?
    If it's small file, you can just create a static counter that reads the lines (again and again).
    Else if its a little bigger file, you might want to put it in a vector (once read, always there).
    If its a very large file, then you might work with RandomAccessFile, and you'll have to know how the file is structered.
    ReadFile and ReadFile2 are 2 examples of read the lines, or place in vector.
    good luck!
    import java.io.*;
    public class ReadFile
        private File file = null;
        private static int executed = 0;
        public ReadFile(String fileName)
            //find the file
            File f = new File(fileName);
            if( !f.exists() )
                System.out.println("Cannot find the specified file ( " + fileName + ").");
            else
                this.file = f;
        public String getTransactionLine()
            executed++;
            String line = "";
            if( this.file == null || executed < 1 )
                return line;
            try
                //create a reader
                BufferedReader br = new BufferedReader( new FileReader(file) );
                int counter = 1;
                //read the lines depends on time it been executed
                while( (line=br.readLine())!=null )
                    if( counter++ == executed )
                        break;
                //if exceeded the amount of lines in the file
                if( executed >= counter )
                    line = "Could not read more, the file contains only " + (counter-1) + " lines.";
            catch (Exception ex)
                ex.printStackTrace();
            return line;
        public static void main(String[] args)
            ReadFile rf = new ReadFile("c:\\debugLog.txt");
            //read 1
            String transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 2
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 3
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 4
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 5
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
    import java.io.*;
    import java.util.Vector;
    public class ReadFile2
        private static int executed = 0;
        private Vector lines = null;
        public ReadFile2(String fileName)
            //find the file
            File file = new File(fileName);
            if( !file.exists() )
                System.out.println("Cannot find the specified file ( " + fileName + ").");
                return;
            //this vector will contain all lines.
            lines = new Vector();
            try
                //create a reader
                BufferedReader br = new BufferedReader( new FileReader(file) );
                String line = "";
                //read the lines and add them to a vector (lines).
                while( (line=br.readLine())!=null )
                    lines.add(line);
            catch (Exception ex)
                ex.printStackTrace();
        public String getTransactionLine()
            String line = "";
            try
                line = (String) lines.get(executed++);
            catch( Exception ex )
                line = "Could not read more, the file contains only " + (executed-1) + " lines.";
            return line;
        public static void main(String[] args)
            ReadFile2 rf = new ReadFile2("c:\\debugLog.txt");
            //read 1
            String transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 2
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 3
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 4
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
            //read 5
            transactionLine = rf.getTransactionLine();
            //output:
            System.out.println(transactionLine);
    }

  • Need to read text file content and have to display it in multiline text box

    dear all,
    Need to read text file content and have to display it in multiline text box.
    actually im new to file handling. i have tried up to get_line and put_line.
    in_file := TEXT_IO.FOPEN ('D:\SAMPLE.txt', 'r');
    TEXT_IO.GET_LINE (in_file,linebuf);
    i dont know how to assign this get_line function to text item
    pls help me in this regards,

    Simply write:
    in_file := TEXT_IO.FOPEN ('D:\SAMPLE.txt', 'r');
    TEXT_IO.GET_LINE (in_file,linebuf);
    :block2.t1 := chr(10)||:block2.t1||chr(10)||linebuf;
    chr(10) --> is for new line character

  • I need to read Pages files but  I can't install Pages on osx 10.6

    I  need to read Pages files, but I can't install Pages because I have OSX 10.6.  Is there some version that will work?

    You can get iWork 09 on the net. You haven't had Pages before? Who is sending you Pages documents? Ask them to export the document to Word or Rtf and you will be able to read the documents in TextEdit, which you have on your computer

  • Need help reading burn CDR mp3 and dvdrw from my superdrive

    my Super Drive was fine untill i upgrade to Maverick now it wouldnt  read the music on all of my burn cdr disk and dvdrw . ALso .need help  reading my external 2TB External Ntfs Hard drive.....

    To many conflicting information...
    my Super Drive was fine untill i upgrade to Maverick
    Per your system profile: "Mac mini, Mac OS 9.1.x"
    Mac Minis do not have a superdrive.  You also posted in the Intel iMac forums.
    Please correct and/or update so that you will be provided w/the correct troubleshooting suggestions.

  • Need help reading files from a simple applet

    hi everyone,
    i have the following problem while trying to read from a file:
    java.security.AccessControlException: access denied (java.io.FilePermission dr.xml read)
    this problem shows up only when loading applet from a browser... if i use appletviewer everithing is ok.
    this is the code:
            cycle = new String[2];
            phase = new String[8];
            v = new Vector();
            int temp;
            try {
                try {
                    fis = new FileInputStream("dr.xml");
                    while ((temp = fis.read()) > 0) {
                        buf += (char) temp;
                    fis.close();
                    fis = null;
                } catch (java.io.FileNotFoundException ex) {
                    System.out.println("File does not exist. ");
            } catch (java.io.IOException ex) {
                System.out.println("error. ");
                ex.printStackTrace();
            }thanks

    You don't have access to the file system. Think about it, you visit a web page and an applet starts reading your files? That's a HUGE security risk.
    That said, I think you can do this if you have a signed/trusted applet. Google "signed applets" and "certificates"

  • Need Help-SOA 11g File Adapter unable to delete input file and its crashing

    Hi All
    Please find the details below:
    1. We have created a simple SOA composite to Read file from an input directory, archive the file in an archive directory using Inbound File Adapter Read
    and then use Outbound File Adapter Write to move the file to a output directory.
    2. File Adapter needs to delete the file after successful read/retrieval.
    3. We are using the "Use Trigger File" for invoking the file adapter. This is a new feature in SOA 11g
    4. Also we are using the option of reading the file as an attachment as we are not doing any transformation in the composite
    Issue Details_
    1. When the trigger file is put in the input directory for the first time, the File Adapter reads the file, archives it and moves it to the output directory
    2. However it does not delete the input file from the input directory and raises Fatal Exception mentioned below:
    [*2011-01-12T16:55:48.639+05:30] [soa_server1] [WARNING] [] [oracle.soa.adapter] [tid: weblogic.work.j2ee.J2EEWorkManager$WorkWithListener@19c243d]*
    [userId: <anonymous>] [ecid: 0000IptyLrL9_aY5TrL6ic1DBOS_000009,0] [APP: soa-infra] File Adapter FileAdapterTriggerFilePOC PostProcessor::
    Delete failed, the operation will be retried for max of [0] times
    [2011-01-12T16:55:48.639+05:30] [soa_server1] [WARNING] [] [oracle.soa.adapter] [tid: weblogic.work.j2ee.J2EEWorkManager$WorkWithListener@19c243d]
    [userId: <anonymous>] [ecid: 0000IptyLrL9_aY5TrL6ic1DBOS_000009,0] [APP: soa-infra] File Adapter FileAdapterTriggerFilePOC [[
    BINDING.JCA-11042
    File deletion failed.
    File deletion failed.
    File : C:\Dibya\AttachmentTest\InputDir\TestFile3.txt could not be deleted.
    Delete the file and restart server. Contact oracle support if error is not fixable.
    If any one has faced similar issues, kindly provide pointers on how to resolve it.
    Regards,
    Dibya

    Hi,
    Using the file adapter, you can poll from multilple locations...
    Keep the following property in your .jca file
    <property name="DirectorySeparator" value="," />
    While giving the path in File Adapter configuration, keep comma and give the next location....then the file will be picked up from the locations you gave....
    Hope this helps...
    Thanks,
    N

  • Need help with connecting file inputs to arrays

    In this assignment I have a program that will do the following: display a list of names inputed by the user in reverse order, display any names that begin with M or m, and display any names with 5 or more letters. This is all done with arrays.
    That was the fun part. The next part requires me to take the names from a Notepad file, them through the arrays and then output them to a second Notepad file.
    Here is the original program: (view in full screen so that the code doesn't get jumbled)
    import java.io.*;       //Imports the Java library
    class progB                    //Defines class
        public static void main (String[] arguments) throws IOException
            BufferedReader keyboard;                                  //<-
            InputStreamReader reader;                                 //  Allows the program to
            reader = new InputStreamReader (System.in);               //  read the the keyboard
            keyboard = new BufferedReader (reader);                  //<-
            String name;                 //Assigns the name variable which will be parsed into...
            int newnames;               //...the integer variable for the amount of names.
            int order = 0;              //The integer variable that will be used to set the array size
            String[] array;             //Dynamic array (empty)
            System.out.println (" How many names do you want to input?");   //This will get the number that will later define the array
            name = keyboard.readLine ();
            newnames = Integer.parseInt (name);                                         // Converts the String into the Integer variable
            array = new String [newnames];                                               //This defines the size of the array
            DataInput Imp = new DataInputStream (System.in);       //Allows data to be input into the array
            String temp;                                       
            int length;                                                                  //Defines the length of the array for a loop later on
                for (order = 0 ; order < newnames ; order++)                                //<-
                {                                                                           //  Takes the inputed names and
                    System.out.println (" Please input name ");                            //  gives them a number according to
                    temp = keyboard.readLine ();                                           //  the order they were inputed in
                    array [order] = temp;                                                  //<-
                for (order = newnames - 1 ; order >= 0 ; order--)                                //<-
                {                                                                                //  Outputs the names in the reverse 
                    System.out.print (" \n ");                                                   //  order that they were inputed
                    System.out.println (" Name " + order + " is " + array [order]);             //<-
                for (order = 0 ; order < newnames ; order++)                                  //<-
                    if (array [order].startsWith ("M") || array [order].startsWith ("m"))     //  Finds and outputs any and all
                    {                                                                         //  names that begin with M or m
                        System.out.print (" \n ");                                            //
                        System.out.println (array [order] + (" starts with M or m"));         //
                    }                                                                         //<-
                for (order = 0 ; order < newnames ; order++)                                            //<-
                    length = array [order].length ();                                                   //
                    if (length >= 5)                                                                    //  Finds and outputs names
                    {                                                                                  //  with 5 or more letters
                        System.out.print (" \n ");                                                      //
                        System.out.println ("Name " + array [order] + " have 5 or more letters ");      //<-
    }The notepad file contains the following names:
    jim
    laruie
    tim
    timothy
    manny
    joseph
    matty
    amanda
    I have tried various methods but the one thing that really gets me is the fact that i can't find a way to connect the names to the arrays. Opening the file with FileInputStream is easy enough but using the names and then outputing them is quite hard. (unless i'm thinking too hard and there really is a simple method)

    By "connect", do you just mean you want to put the names into an array?
    array[0] = "jim"
    array[1] = "laruie"
    and so on?
    That shouldn't be difficult at all, provided you know how to open a file for reading, and how to read a line of text from it. You can just read the line of text, put it in the array position you want, until the file is exhausted. Then open a file for writing, loop through the array, and write a line.
    What part of all that do you need help with?

  • Need help replacing a file in AE

    Ok, here is my problem, I made a project on another computer and then I transfered to my computer. I dragged all of the images and sounds but ONE very important image. I downloaded that same image from online and I need help replacing the corrupted old image with the new one. Here is a picture with more detail.
    I tried copy & pasting the layer properties and effects, but that didn't work. Any ideas?
    Thanks,
    Emal

    For instructions on swapping out a footage item's source file, "Replace layer source with reference to another footage item".

  • Need help with copying files onto external drive

    I need help! Trying to copy downloaded movie files from Vuze (which have downloaded successfully) and copy onto external hard drive to view them but it wont let me copy over to the external device. Any ideas how to fix this please???

    Can you explain the steps you used, and the error message (or symptom), that says the copy did not work? 

  • Need help converting project file from Creative Cloud to CS6

    Hello.
    I started a project file on the Adobe Creative Cloud and I am trying to convert the file to CS6 (as that is what all my editors have). I have all of my time codes generated in Creative Cloud and I need the easiest solution to share the file across platforms with out corrupting it. Any help is appreciated. Thank you.
    -A*

    I am the director of the project- so I am not very technically inclined to answer these questions, but will try my best. My lead editor dropped out of the project leaving me very confused and I am trying to establish a new workflow based off of her existing project file.
    The original project was started in Adobe Creative Cloud. I am now trying to use Adobe CS6 and I am trying to figure out if we can convert a file from Creative Cloud > CS6. If you can provide a list of questions for me to ask my previous editor I can direct them to her and try to provide a more concise answer. Thanks for your help.

  • I need help retrieving Microsoft files lost when upgrading to OSX Mavericks

    My daughter recently upgraded our Mac to the OSX Mavericks platform. Unfortunately, all of our Microsoft files, etc. are gone! I need to know how I can retrieve these files or if I can. I'm honestly not impressed with this new platform. I need help asap and your help is truly appreciated.

    You have to make the backup yourself. That's your only protection against file loss whether accidental or catastrophic. In fact you should have at least two of them - each done differently and on separate drives.
    If your files truly were "erased" then you can see if they can be recovered:
    General File Recovery
    If you stop using the drive it's possible to recover deleted files that have not been overwritten by using recovery software such as MAC Data Recovery, Data Rescue II, File Salvage or TechTool Pro.  Each of the preceding come on bootable CDs to enable usage without risk of writing more data to the hard drive.  Two free alternatives are Disk Drill and TestDisk.  Look for them and demos at MacUpdate or CNET Downloads. Recovery software usually provide trial versions that enable you to determine if the software would help before actually paying for it. Beyond this or if the drive has completely failed, then you would need to send the drive to a recovery service which is very expensive.
    The longer the hard drive remains in use and data are written to it, the greater the risk your deleted files will be overwritten.
    Also visit The XLab FAQs and read the FAQ on Data Recovery.
    Basic Backup
    For some people Time Machine will be more than adequate. Time Machine is part of OS X. There are two components:
    1. A Time Machine preferences panel as part of System Preferences;
    2. A Time Machine application located in the Applications folder. It is
         used to manage backups and to restore backups. Time Machine
         requires a backup drive that is at least twice the capacity of the
         drive being backed up.
    3. Time Machine requires a backup drive that is at least double the
         capacity of the drive(s) it backs up.
    Alternatively, get an external drive at least equal in size to the internal hard drive and make (and maintain) a bootable clone/backup. You can make a bootable clone using the Restore option of Disk Utility. You can also make and maintain clones with good backup software. My personal recommendations are (order is not significant):
      1. Carbon Copy Cloner
      2. Get Backup
      3. Deja Vu
      4. SuperDuper!
      5. Synk Pro
      6. Tri-Backup
    Visit The XLab FAQs and read the FAQ on backup and restore.  Also read How to Back Up and Restore Your Files. For help with using Time Machine visit Pondini's Time Machine FAQ for help with all things Time Machine.
    Although you can buy a complete external drive system, you can also put one together if you are so inclined.  It's relatively easy and only requires a Phillips head screwdriver (typically.)  You can purchase hard drives separately.  This gives you an opportunity to shop for the best prices on a hard drive of your choice.  Reliable brands include Seagate, Hitachi, Western Digital, Toshiba, and Fujitsu.  You can find reviews and benchmarks on many drives at Storage Review.
    Enclosures for FireWire and USB are readily available.  You can find only FireWire enclosures, only USB enclosures, and enclosures that feature multiple ports.  I would stress getting enclosures that use the Oxford chipsets especially for Firewire drives (911, 921, 922, for example.)  You can find enclosures at places such as;
      1. Cool Drives
      2. OWC
      3. WiebeTech
      4. Firewire Direct
      5. California Drives
      6. NewEgg
    All you need do is remove a case cover, mount the hard drive in the enclosure and connect the cables, then re-attach the case cover.  Usually the only tool required is a small or medium Phillips screwdriver.

  • Help reading .csv file into an arraylist

    i need to read a csv file into an arraylist and then print the arraylist to the screen.
    using:
    try {
                // Setup our scanner to read the file at the path c:\test.txt
                Scanner myscanner = new Scanner(new File("\\carsDB.csv"));    
    ArrayList<CarsClass> carsClass = new ArrayList<CarsClass>(" write all fields");   
                while (myscanner.hasNextLine()) {
    myscanner.add(" add car fields to the carClass");              // Write your code here.
    // loop to read them all to the screencsv file is like this:
    Manufacturer,carline name,displ,cyl,fuel,(miles),Class
    CHEVROLET,CAVALIER (natural gas),2.2,4,CNG,120,SUBCOMPACT CARS
    HONDA,CIVIC GX (natural gas),1.6,4,CNG,190,SUBCOMPACT CARS
    FORD,CONTOUR (natural gas),2,4,CNG,70,COMPACT
    FORD,CROWN VICTORIA (natural gas),4.6,8,CNG,140/210*,LARGE CARS
    FORD,F150 PICKUP (natural gas) - 2WD,5.4,8,CNG,130,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 PICKUP (natural gas) - 2WD,5.4,8,CNG,160,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 PICKUP (natural gas) - 2WD,5.4,8,CNG,150/210*,STANDARD PICKUP TRUCKS 2WD
    FORD,F150 PICKUP (natural gas) - 4WD,5.4,8,CNG,130,STANDARD PICKUP TRUCKS 4WD
    FORD,F250 PICKUP (natural gas) - 4WD,5.4,8,CNG,160,STANDARD PICKUP TRUCKS 4WD
    FORD,E250 ECONOLINE (natural gas) - 2WD,5.4,8,CNG,170,"VANS, CARGO TYPE"
    FORD,E250 ECONOLINE (natural gas) - 2WD,5.4,8,CNG,80,"VANS, CARGO TYPE"
    FORD,F150 LPG - 2WD,5.4,8,LPG,290/370*,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 LPG - 2WD,5.4,8,LPG,260/290/370**,STANDARD PICKUP TRUCKS 2WD
    ok, so do i need to write a file carsclass.java or is the line:
    ArrayList<CarsClass> carsClass = new ArrayList<CarsClass>(" write all fields");
    going to define my carsclass objects? how do i write my fields for each of the 7 categories?
    i believe i can easily add to and print the arraylist, but i'm confused how to go about creating this arraylist in the first place. do i just create carclass.java and save them all as strings? i guess my question is mainly how should i structure this? any suggestions/help is appreciated.
    Edited by: scottc on Nov 15, 2007 5:55 PM

    String.split uses regular expressions.Ahh yeah ummm (slaps forehead) I'd forgotten that... so maybe StringTokeniser is more accessible for noob's. Sorry.
    Anyway... if all you want/need to so is store a bunch of String field values then how about using an array of String's instead of individual fields... maybe something like:
    forums\Car.java
    * Car Data Transfer Object. All fields are final, making objects of this class
    * thread safe(r).
    * @author keith
    package forums;
    import krc.utilz.stringz.Arrayz;
    public class Car
      // class attributes                       // variables //isn't actually wrong, it's just not quit right.
      private final String[] fields;            // final means values are write once, read many times, which is thread safe(r).
       * Initialises the new Cars fields to the given fields array.
       * @param fields - an array of any (reasonable) length
      public Car(String[] fields) {             // no need to comment a constructor as a constructor.
        this.fields = fields;                   // much better to provide javadoc comments explaining
      }                                         // what the method does and how to use it.
       * Returns this Car's fields as one long string.
      public String toString() {                // It's actually GOOD to be a lazy programmer.
        return Arrayz.join(", ", this.fields);  // I have reused my Arrayz.join in several projects.
                                                // I think you can use Array.toString (new in 1.6) instead.
    krc\utilz\stringz\Arrayz.java
    package krc.utilz.stringz;
    import java.util.List;
    import java.util.ArrayList;
    public class Arrayz
        * returns true if the given value is in the args list, else false.
        * @param value - the value to seek
        * @param args... - variable number of String arguments to look in
      public static boolean in(String value, String... args) {
        for(String a : args) if(value.equals(a)) return true;
        return false;
        * append the elements of array into one string, seperated by FS
        * @param a  - an array of strings to join together
        * @param FS - Field Seperator string, optional default=" "
        * @example
        *  String[] array = {"Bob","The","Builder"};
        *  System.out.println(join(array);
        *  --> Bob The Builder
        *  System.out.println("String[] array = {\""+join(array, "\",\"")+"\"};");
        *  --> String[] array = {"Bob","The","Builder"};
      public static String join(String FS, String[]... arrays) {
        StringBuffer sb = new StringBuffer();
        for (String[] array : arrays)
          sb.append(join(array, FS));
        return(sb.toString());
      public static String join(String[] array) {
        return(join(array, " "));
      public static String join(String[] a, String FS) {
        if (a==null) return null;
        if (a.length==0) return "";
        StringBuffer sb = new StringBuffer(a[0]);
        for (int i=1; i<a.length; i++) {
          sb.append(FS+a);
    return sb.toString();
    * append all the elements of the given arrays into one big array
    * @param String[]... arrays - to be concatenated
    * @return String[] - one big array
    public static String[] concatenate(String[]... arrays) {
    List<String> list = new ArrayList<String>();
    for(String[] array : arrays) {
    for(String item : array) {
    list.add(item);
    return(list.toArray(new String[0]));
    I guess that Arrayz class might be a bit beyond you at the moment so don't worry too much if you can't understand the code... there are no nasty surprises in it... just cut and paste the code, change the package name, and use it (for now).

  • URGENT: Need help reading URL of current page

    Hello kind people!
    I need help, and its very simple:
    How do i read the URL of a web page?
    For example, the URL of this page is:
    http://forums.sun.com/thread.jspa?threadID=5327796
    So how can i be able to read in this URL in my java program?
    thanks SO MUCH
    P.S. I HAVE searched the java docs and everything, the closest thing i found was request.getRequestURL().? but i have no idea how to use it. you have NO IDEA how appreciative i would be if you could simply show me exactly how to read in the URL of a given page.
    thanks SO MUCH
    Edited by: homegrownpeas on Aug 31, 2008 5:19 PM

    Going by what I understand here is a simple version of how you can read data from over HTTP.
    This expects the "page" to be text (hence an InputStreamReader instead of an InputStream.)
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.HashMap;
    * GPLv2.
    * @author karlm816
    public class HomeGrownPeas {
          * @param args
         public static void main(String[] args) {
              HashMap<String, String> params = new HashMap<String, String>();
              params.put("threadID", "5327796");
              System.out.println(loadHttpPage("http://forums.sun.com/thread.jspa", params));     
         public static String loadHttpPage(String sUrl, HashMap<String, String> params) {
              // Build the HTTP request string
              StringBuilder sb = new StringBuilder();
              if (params != null) {
                   for (String key : params.keySet()) {
                        if (sb.length() > 0) {
                             sb.append("&");
                        sb.append(key);
                        sb.append("=");
                        sb.append(params.get(key));
              System.out.println("params: " + sb.toString());
              try {
                   URL url = new URL(sUrl);
                   URLConnection connection = url.openConnection();
                   connection.setDoOutput(true);
                   connection.setRequestProperty("Content-Length", "" + sb.length());
                   connection.setUseCaches(false);
                   if (connection instanceof HttpURLConnection) {
                        HttpURLConnection conn = (HttpURLConnection) connection;
                        conn.setRequestMethod("POST");
                   OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
                   osw.write(sb.toString());
                   osw.close();
                   // Now use sb to hold the resutls from the request
                   sb = new StringBuilder();
                   BufferedReader in = new BufferedReader(
                         new InputStreamReader(
                         connection.getInputStream()));
                   String s;
                   while ((s = in.readLine()) != null) {
                        sb.append(s);
                        // To make it more "human readable"
                        sb.append("\n");
                   in.close();
             } catch (IOException e) {
                  e.printStackTrace();
                  return null;
            return sb.toString();
    }

Maybe you are looking for

  • Looking for a simple password reset tool

    I work for a public school district. We want the librarians at each campus to reset passwords for students to take the load off of the help desk. We used to be a Novell network and we had a simple password reset gui tool that they used. Now it seems

  • Page Appearance

    I am using Dreamweaver CS5.  Let me apologize, I am a guy who using the design mode to design sites for the most part so forgive me if I don't use the correct html terms. I created a template and have built multiple pages from it.  All display correc

  • Wrong Pricing Procedure getting picked up in Value Contract

    While creating Value Contract, when we maintain conditions, the condition type which we want to maintain are missing. During a year, PO is made a for a value of around 15 crores. So we need to make  contract which will pick up the same pricing proced

  • Syntax error using try statement in WLST

    Hi All, I have a WLST script to create some JMS resources. I want to implement exception handling in such a way that if the script fails at any point, all the changes done should be reverted back. However, whenever I am trying to put a try block, the

  • Interactive maps

    hi Experts, My query is as follows: I want to make interactive map ie Clicking on some country or region's hot spot on the map should retreive certain data from the database based on the selection. Now my question is   How to create a hot spot for th