Read .txt file of numbers and draw

Hello.
I am trying to utlize BufferedReader and g.drawline to read numbers from a text file and output to the screen as a "line".
I know I still need a while loop and some error checking, but, am having trouble finishing the more 'basic' portion of the code.
The GUI class is already taken care of. I am just trying to open the file, read, turn to int, produce lines, then close file.
I have commented out some of the code that was provided with the assignment.
Any help would be appreciated.
Thank you.
import javax.swing.*;
import java.awt.*;
* DrawingPanel creates a panel used for drawing
* a map
* Numbers stored in text file, usa.txt.
* one number per line.  Read each number
* create a map on screen. GUI provided in a
* 2nd class.
public class DrawingPanel extends JPanel {
     /** Graphics object used for drawing on the panel */                           
     private Graphics g;                  
     /** Tells if it is time to draw */
     private boolean timeToDrawPath;
     /** The filename of the hurricane path */
                              //private String pathFile; 
     private String usa.txt;
     * Creates a new, white DrawingPanel for drawing the maps
     public DrawingPanel() {
          setBackground(Color.white);
          this.timeToDrawPath = false;
                              //this.pathFile = null;
          this.usa.txt = null;
     * This method is called automatically by Java.  There will NEVER
     * be a direct call to paint() anywhere in the code.  Anytime that we
     * need to update what is drawn on the screen, we call repaint().
     * @param grph The graphics window to paint
     public void paint(Graphics grph) {
          g = grph;
          super.paint(g);
          processUSA();
          if (timeToDrawPath){
               drawPath();
     * Reads the USA coastline coordinates from a file and draws the path
     * to the panel
     public void processUSA( ) {
                    //just an example of how to draw a single
                    //line segment from (50,50) to (200,200)
                    //g.drawLine( 300, 50, 200, 200);
     //Insert the while loop here??
     //Include the parse.Int statement
     //Open the file
     String inFile = ("usa.txt");
     FileReader fileReader = new FileReader (inFile);
               //BufferedReader bufReader = newBufferedReader (fileReader);
     BufferedReader bufReader=newBufferedReader (new fileReader ("usa.txt"));
                    //Insert beginning of while loop here????
     //read data from the file
     String str=bufReader.readLine();
     g.drawLine(x1,y1,x2,y2);
     }

Yep, you are right in deciding the positioning of the while loop.
But the folly you are committing is while creating object of BufferedReader ... It is to be created by passing to the constructor, the reference of the FileReader object you have created.
so the line of code shud look like ...
BufferedReader bufReader = new BufferedReader(FileReaderObject);
And then you can go ahead with readLine() as per your requirement in the while loop.

Similar Messages

  • Read from file, compare string and return a part

    Hello, is there a reasonable good way to read text file containing information, and if string comparison is successfull, return a nother part of the string.
    What i have done so far:
    set file_name to (path to desktop as text) & "filename.txt"
    set F to open for access tiedosto with write permission
    set file_information to (read F)
    close access F
    (i will be moving this to Application Support/Appname/ when i figure it out).
    The data in the file is in following format
    12234567890Name1
    98765432123Name2
    92347928347Name3
    What im stuck now is:
    I need to compare each line the 10 numbers with search string, if match is found, the name part should be returned.
    Any idea's?

    You already read in the text file, so you need to put the data thru a repeat loop:
    repeat with name_part in paragraphs of file_information
    -- ((character 1 thru 10 of name_part) as string) is the first 10 digits of name part
    if ((character 1 thru 10 of name_part) as string) is search_string then return name_part
    end

  • Reading .txt file Server side

    How do you read a file server side and send it to the client. I am getting confused with FileReader and the fact that you have to wrap a socket with PrintWriter, BufferedWriter and OutputStreamWriter i.e.
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    Any ideas

    Assuming you want to read from a file on the server and write to a client socket:
    FileReader fi= new FileReader("reading.txt");
    BufferedReader br= new BufferedReader(fi);
    String il=br.readLine();
    ServerSocket sock= new ServerSocket(port,mcons);
    PrintStream dout=
    new PrintStream (sock.getOutputStream());
    dout.println(il);
    dout.flush();...
    Hope this helps.

  • Reading TXT files on WEBmode

    Hy
    My problem is to read TXT-Files in Webmode. In Client-Server mode it works fine. I use the function "text_io". In Webmode i get an error "No data found" (i think it is FRM-40375).
    In which virtual directory should the files placed on the OAS????
    Does anybody have some examples for me???

    You need to specify the directory unless your files are in the current working directory of the servlet container.
    The following can help you see some of your application context:
            // Get the server configuration information and display it.
            String thisServer= getServletConfig().getServletContext().getServerInfo();
            System.out.println("The servlet Engine version: " + thisServer);
            // What is the servlet root path ?
            String prefix =  getServletContext().getRealPath("/");
            System.out.println("prefix = '" + prefix + "'");
            // What is the app root ?
            String AppRootDir = getServletConfig().getServletContext().getRealPath("/");
            System.out.println("The app root directory : " + AppRootDir );

  • [svn] 4561: Updated error. txt files for goodValidatorTest and patternFilterLoggingMessageFilterTest to fix failure on appservers other than Tomcat

    Revision: 4561
    Author: [email protected]
    Date: 2009-01-16 10:59:37 -0800 (Fri, 16 Jan 2009)
    Log Message:
    Updated error.txt files for goodValidatorTest and patternFilterLoggingMessageFilterTest to fix failure on appservers other than Tomcat
    checkintests: pass
    Modified Paths:
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/messagingService/validation/good ValidatorTest/error.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/messagingService/validation/patt ernFilterLoggingMessageFilterTest/error.txt

    Dude this worked fantastic.   Thank you for posting.

  • Is it possible to read txt files on the new ipod nano? as it was on the 5th gen

    is it possible to read txt files on the new ipod nano? as it was on the 5th gen.

    We won't know for sure until either the iPod is released and somebody can verify that or when the manual is available online from Apple.
    B-rock

  • File Adapter - Reading 2 files from sender and one file to receiver

    All - I am looking for a best solution for reading two files from sender and generating one file to the receiver.
    Here is the scenario
    Sender file s - A is a master file. B is a detail file; B will have a one to many records for each record of File A.. that is the relation ship between 2 files..  I am looking for a better solution to
    Example
    Input:
    File A will have a record like "summary1 ABC 1234"
    File B will have a record like "Detailfor Summary1 CDF 8679"
    Output:
    File C shall have a record "consolidatedofSummary&Detail ABC 1234 8679"
    1) read records of master row and detail row from these 2 files
    2) do the mapping to the receiver output format which it is creating for records with some harcoded values and based on the values from master and detail rows of sender file
    if I can accomblish reading sender files and do the mapping to the receiver , assume that mapping to the receiver format would not be cumbersome.
    please help me...
    Thanks

    Hi Gopal,
    Ur approach to the interface is perfect.... Go ahead.
    For selecting multiple files in source use Advanced Selection for files.. and specify the directory paths and also the file name shema...
    This will fetch the 2 files into the integration engine... then u map the 2 source files to one target file(2:1 mapping).
    Specify accordingly the receiver side FCC and test it end to end...
    If u face any prblm post here... some1 will help u out..
    Babu

  • How do I convert my Adobe PDF files to Numbers and Pages

    I use Adobe and i am having issues converting their PDF files to Numbers and or Pages.......

    If you have Adobe Acrobat Pro, it can export to Word .doc and from that you can open the file in Pages.
    Otherwise open the pdf in Preview app and manually select and copy the text over to Pages.
    Peter

  • Reading in a txt file, appending numbers to it.

    So I'm a student at Georgia Tech working on a relatively simple Java program for a research internship, but it's been awhile since I've had my Java course and I'd really like some help on this. Basically, what I'm looking to do is to take in a text file with data that only consists of the numbers 1,2,4 and 5, with up to four digits in each line and no number may be repeat itself in the same line. A sample of data would look like the following:
    12
    21
    154
    2
    1
    45
    24
    4125
    Lines like '12' and '21' would count as the same however, as would '4512' to '1245'. I'm trying to determine how often each number 'interacts' with each other number, and then append that data to the end of the text file by saying something along the lines of:
    One-Two Interactions = 4
    Four-Five Interactions = 6
    Etc. etc. The real problem I'm having is I can't remember how to get the BufferedReader to 'identify' the particular numbers and combinations of numbers before adding to the count in each variable. If you have any advice or answers, it would be greatly appreciated.

    import java.io.*;
    import java.util.*;
    public class ExchangeProgram{
         public static void main(String[] args) {
              int one = 0;
              int two = 0;
              int four = 0;
              int five = 0;
              int one_two = 0;
              int four_five = 0;
              int one_four = 0;
              int two_five = 0;
              int four_two = 0;
              int one_five = 0;
              int one_two_four = 0;
              int two_four_five = 0;
              int one_two_five = 0;
              int one_four_five = 0;
              int all = 0;
              Set h = new HashSet();
              File file = new File("test.txt");
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;
    try
    reader = new BufferedReader(new FileReader(file));
    String text = null;
    // repeat until all lines is read
    while ((text = reader.readLine()) != null)
                             h.add(text);
    } catch (FileNotFoundException e)
    e.printStackTrace();
    } catch (IOException e)
    e.printStackTrace();
    } finally
    try
    if (reader != null)
    reader.close();
    } catch (IOException e)
    e.printStackTrace();
              for (int i=0; i>h.size(); i++){
                        if (h.contains("1")){
                             one++;
                        if (h.contains("2")){
                             two++;
                        if (h.contains("4")){
                             four++;
                        if (h.contains("5")){
                             five++;
                        if (h.contains("12")){
                             one_two++;
                        if (h.contains("45")){
                             four_five++;
                        if (h.contains("14")){
                             one_four++;
                        if (h.contains("25")){
                             two_five++;
                        if (h.contains("42")){
                             four_two++;
                        if (h.contains("15")){
                             one_five++;
                        if (h.contains("124")){
                             one_two_four++;
                        if (h.contains("245")){
                             two_four_five++;
                        if (h.contains("125")){
                             one_two_five++;
                        if (h.contains("145")){
                             one_four_five++;
                        if (h.contains("1245")){
                             all++;
    // show file contents here
    System.out.println(one_two);
    Here's what I've come up with so far, though I'm getting this error: Note: Recompile with -Xlint:unchecked for details.
    Any comments on any major mistakes I'm making here? Haven't used the Set interface much before.

  • How do I read txt file and add items to dropdownlist or checkbox

    I want to add items to a dropdown or check box by reading from a text file(and select one of them). (I donot use any table or database). The list of items is sometimes upto 20MB and hence cannot populate using session bean.I want items to be added to either checkbox or listbox during a button action. I have done this for textarea but unable so far to acheive for checkbox or listbox. I use following code which does not work:
    public String button3_action() {       
    try{           
    FileReader fr = new FileReader "F:/CreatorProjects/checkboxtst.prs");
    BufferedReader br = new BufferedReader(fr);
    String s;
    while((s=br.readLine())!=null) {
    dropdown1.setValue(s);
    br.close();
    fr.close();
    }catch(Exception e) {
    e.printStackTrace();
    return null;
    I know I cant just transplant textarea code for dropdownlist or checkbox.
    Any help is greatly appreciated.
    Thanks.
    Dr.AM.Mohan Rao

    I am able to read from txt file to a listbox if i write in sessionsbean1:
    try{
    FileReader fr = new FileReader("F:/CreatorProjects/checkboxtst.prs");
    BufferedReader br = new BufferedReader(fr);
    String s1="";
    String s="";
    while((s=br.readLine())!=null) {
    s1 = s1+s;
    s1= s1+"\n";
    disOptions = new com.sun.rave.web.ui.model.Option[] {              
    new Option(s1,s1)};
    diseases = new String[] {};
    fr.close();
    br.close();
    catch(Exception e) {
    e.printStackTrace();
    But I get all data in one line!! if I click submit button text area gets all. How to display items in each line????Please help...
    Dr.AM. Mohan Rao

  • Reading .txt file and non-english chars

    i added .txt files to my app for translations of text messages
    the problem is when i read the translations, non-english characters are read wrong on my Nokia. In Sun Wireless Toolkit it works.
    See the trouble is because I don't even know what is expected by phone...
    UTF-8, ISO Latin 2 or Windows CP1250?
    im using CLDC1.0 and MIDP1.0
    What's the rigth way to do it?
    here's what i have...
    String locale =System.getProperty("microedition.locale");
    String language = locale.substring(0,2);
    String localefile="lang/"+language+".txt";
    InputStream r= getClass().getResourceAsStream("/lang/"+language+".txt");
    byte[] filetext=new byte[2000];
    int len = 0;
    try {
    len=r.read(filetext);
    then i get translation by
    value = new String(filetext,start, i-start).trim();

    Not sure what the issue is with the runtime. How are you outputing the file and accessing the lists? Here is a more complete sample:
    public class Foo {
         final private List colons = new ArrayList();
         final private List nonColons = new ArrayList();
         static final public void main(final String[] args)
              throws Throwable {
              Foo foo = new Foo();
              foo.input();
              foo.output();
         private void input()
              throws IOException {
             BufferedReader reader = new BufferedReader(new FileReader("/temp/foo.txt"));
             String line = reader.readLine();
             while (line != null) {
                 List target = line.indexOf(":") >= 0 ? colons : nonColons;
                 target.add(line);
                 line = reader.readLine();
             reader.close();
         private void output() {
              System.out.println("Colons:");
              Iterator itorColons = colons.iterator();
              while (itorColons.hasNext()) {
                   String current = (String) itorColons.next();
                   System.out.println(current);
              System.out.println("Non-Colons");
              Iterator itorNonColons = nonColons.iterator();
              while (itorNonColons.hasNext()) {
                   String current = (String) itorNonColons.next();
                   System.out.println(current);
    }The output generated is:
    Colons:
    a:b
    b:c
    Non-Colons
    a
    b
    c
    My guess is that you are iterating through your lists incorrectly. But glad I could help.
    - Saish

  • Writing and reading txt file, GUI components

    <b>HI GUYS I AM JUST NEW TO JAVA AND I AM TRYING TO LEARN SOME MORE IN JAVA. SO I NEED HELP FROM YOU GREAT GUYS WHO KNOWS MORE & MORE THING THAN ME. I CODE A GUI FOR THIS PROGRAM. THE CODE IS BELOW. <b/>
    This program has to read a txt file to create Food objects which will consist of a food name, a serving size, and a number of calories. A text file is read which contains the calories contained in specific food items. From this data, an array of Food objects will be created and used to populate a combo box for user selection. The Food objects will also be used in calculating the balance calories for a given user on a given day.
    User input will be used to create User objects which will be user name, age, gender, height, weight, and Food Diary objects (composition). The Food Diary objects will consist of Date (composition), Food object (composition), number of servings, and a balance. Food Diary objects will consist of the activity on any given day (see text area in sample output screen below). All User objects are saved to a file as objects and can be retrieved on subsequent runs of the program.
    The program will calculate the number of calories the user is allowed per day to maintain the user�s current weight (see below for formula to use for this).
    BMRMen = 66 + (13.7 * weightPounds/2.2) + (5 * heightInches*2.54) - (6.8 * age)
    BMRWomen = 655 + (9.6 * weightPounds/2.2) + (1.8 * heightInches*2.54) - (4.7 * age)
    GUI CODE
    <code>
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FoodDiaryGUI extends JFrame implements ActionListener {
    JLabel lblName, lblAge, lblWeight,lblHeight,lblFemale,lblMale,lblFood;
    JTextField txtName, txtAge, txtWeight,txtHeight;
    JButton btnSave, btnNewUser;
    JTextArea outputArea;
    JComboBox cbFood;
    int currentIndex=0, lastIndex=4;
    public FoodDiaryGUI()
    super ("Food Diary Calculator");
    lblName= new JLabel("Name: ");
    lblAge= new JLabel("Age: ");
    lblWeight= new JLabel("Weight(lbs): ");
    lblHeight= new JLabel("Height(inches): ");
    lblFemale= new JLabel("Female: ");
    lblMale= new JLabel("Male: ");
    lblFood= new JLabel("Choose a Food: ");
    txtName= new JTextField(15);
    txtAge= new JTextField(3);
    txtWeight= new JTextField(6);
    txtHeight= new JTextField(6);
    outputArea= new JTextArea(9,20);
    cbFood= new JComboBox();
    cbFood.setPreferredSize(new Dimension(100, 20));
    Container c = getContentPane();
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new FlowLayout());
    btnSave= new JButton("SAVE");
    northPanel.add(btnSave);
    btnNewUser= new JButton("NEW USER");
    northPanel.add(btnNewUser);
    btnSave.addActionListener(this);
    btnNewUser.addActionListener(this);
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new FlowLayout());
    centerPanel.add(lblName);
    centerPanel.add(txtName);
    centerPanel.add(lblAge);
    centerPanel.add(txtAge);
    centerPanel.add(lblWeight);
    centerPanel.add(txtWeight);
    centerPanel.add(lblHeight);
    centerPanel.add(txtHeight);
    centerPanel.setLayout(new FlowLayout());
    JRadioButton rbMale = new JRadioButton(maleString);
    birdButton.setMnemonic(KeyEvent.VK_M);
    birdButton.setActionCommand(maleString);
    birdButton.setSelected(true);
    JRadioButton rbFemale = new JRadioButton(femaleString);
    catButton.setMnemonic(KeyEvent.VK_F);
    catButton.setActionCommand(femaleString);
    //Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(rbMale);
    group.add(rbFemale);
    //Register a listener for the radio buttons.
    rbMale.addActionListener(this);
    rbFemale.addActionListener(this);
    public void actionPerformed(ActionEvent rb) {
    picture.setIcon(new ImageIcon("images/"
    + rb.getActionCommand()
    + ".gif"));
    radioGroup.add(rbMale);
    radioGroup.add(rbFemale);
    centerPanel.add(rbMale);
    centerPanel.add(rbFemale);
    centerPanel.add(lblFood);
    centerPanel.add(cbFood);
    JPanel southPanel = new JPanel();
    southPanel.setLayout(new FlowLayout());
    southPanel.add (outputArea);
    c.add(northPanel,BorderLayout.NORTH);
    c.add(centerPanel,BorderLayout.CENTER);
    c.add(southPanel,BorderLayout.SOUTH);
    setSize(650,300);
    setVisible(true);
    //add listener to button components.
    public void actionPreformed(ActionEvent e)
    if (e.getSource()==btnSave)
    currentIndex++;
    currentIndex--;
    public static void main (String[] args)
    FoodDiaryGUI application = new FoodDiaryGUI();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    </code>
    THE .txt file is as:
    1000 ISLAND, SALAD DRSNG,LOCAL*1 TBSP*25
    1000 ISLAND, SALAD DRSNG,REGLR*1 TBSP*60
    100% NATURAL CEREAL *1 OZ*135
    40% BRAN FLAKES, KELLOGG'S*1 OZ*90
    40% BRAN FLAKES, POST*1 OZ*90
    ALFALFA SEEDS, SPROUTED, RAW*1 CUP*10
    ALL-BRAN CEREAL*1 OZ*70
    ALMONDS, WHOLE*1 OZ*165
    ANGELFOOD CAKE, FROM MIX*1 PIECE*125
    APPLE JUICE, CANNED*1 CUP*115
    i hope this forum site has to many java professionals and this problem is nothing for them. for me it is great.

    Stick to using a single userid and a single posting of a question:
    http://forum.java.sun.com/thread.jspa?threadID=731264&tstart=0

  • Reading .txt files and put it into a TextArea

    Hi all,
    I got a problem! I have to make something like a messenger.
    I want to put the written text into a .txt file, after that I have to get the text out of the .txt file and put in into a TextArea.
    I would ike it to to that like this:
    ">User 1
    Hello!
    >User 2
    Hi!
    Now here are my questions:
    1: What is the moet easy way to do this ?
    2: How could i put Enters into a .txt file with Java ?
    3: How could i read all the text from the .txt file and put it into a TextArea WITH ENTERS ?
    Thanks for your help!
    Greetings, Jasper Kouwenberg

    use JTextArea.read(new FileReader(fileName)) for reading.
    and JTextArea.write(new FileWriter(fileName)) for writing.
    The enters should be ok if the user press enter and adds a new line ("\n") to the text area component.
    It will save the enter in the text file and load it correctly back to the text area.
    If you want to add enter programmatically just add "\n" string to the text area component.

  • (Urgent help needed) how to read txt file and store the data into 2D-array?

    Hi, I have a GUI which allow to choose file from the file chooser, and when "Read file" button is pressed, I want to show the array data into the textarea.
    The sample data is like this followed:
    -0.0007     -0.0061     0.0006
    -0.0002     0.0203     0.0066
    0     0.2317     0.008
    0.0017     0.5957     0.0008
    0.0024     1.071     0.0029
    0.0439     1.4873     -0.0003
    I want my program to scan through and store these data into 2D array.
    However for some reason, my source code issues errors, and I don't know what's wrong with it, seems to have a problem in StringTokenizer though. Can anybody help me?
    Thanks in advance.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.StringTokenizer;
    public class FileReduction1 extends JFrame implements ActionListener{
    // GUI features
    private BufferedReader fileInput;
    private JTextArea textArea;
    private JButton openButton, readButton,processButton,saveButton;
    private JTextField textfield;
    private JPanel pnlfile;
    private JPanel buttonpnl;
    private JPanel buttonbar;
    // Other fields
    private File fileName;
    private String[][] data;
    private int numLines;
    public FileReduction1(String s) {
    super(s);
    // Content pane
         Container cp = getContentPane();
         cp.setLayout(new BorderLayout());     
    // Open button Panel
    pnlfile=new JPanel(new BorderLayout());
         textfield=new JTextField();
         openButton = new JButton("Open File");
    openButton.addActionListener(this);
    pnlfile.add(openButton,BorderLayout.WEST);
         pnlfile.add(textfield,BorderLayout.CENTER);
         readButton = new JButton("Read File");
    readButton.addActionListener(this);
         readButton.setEnabled(false);
    pnlfile.add(readButton,BorderLayout.EAST);
         cp.add(pnlfile, BorderLayout.NORTH);
         // Text area     
         textArea = new JTextArea(10, 100);
    cp.add(new JScrollPane(textArea),BorderLayout.CENTER);
    processButton = new JButton("Process");
    //processButton.addActionListener(this);
    saveButton=new JButton("Save into");
    //saveButton.addActionListener(this);
    buttonbar=new JPanel(new FlowLayout(FlowLayout.RIGHT));
    buttonpnl=new JPanel(new GridLayout(1,0));
    buttonpnl.add(processButton);
    buttonpnl.add(saveButton);
    buttonbar.add(buttonpnl);
    cp.add(buttonbar,BorderLayout.SOUTH);
    /* ACTION PERFORMED */
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("Open File")) getFileName();
         if (event.getActionCommand().equals("Read File")) readFile();
    /* OPEN THE FILE */
    private void getFileName() {
    // Display file dialog so user can select file to open
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
         int result = fileChooser.showOpenDialog(this);
         // If cancel button selected return
         if (result == JFileChooser.CANCEL_OPTION) return;
    if (result == JFileChooser.APPROVE_OPTION)
         fileName = fileChooser.getSelectedFile();
    textfield.setText(fileName.getName());
         if (checkFileName()) {
         openButton.setEnabled(false);
         readButton.setEnabled(true);
         // Obtain selected file
    /* READ FILE */
    private void readFile() {
    // Disable read button
    readButton.setEnabled(false);
    // Dimension data structure
         getNumberOfLines();
         data = new String[numLines][];
         // Read file
         readTheFile();
         // Output to text area     
         textArea.setText(data[0][0] + "\n");
         for(int index=0;index < data.length;index++)
    for(int j=1;j<data[index].length;j++)
    textArea.append(data[index][j] + "\n");
         // Rnable open button
         openButton.setEnabled(true);
    /* GET NUMBER OF LINES */
    /* Get number of lines in file and prepare data structure. */
    private void getNumberOfLines() {
    int counter = 0;
         // Open the file
         openFile();
         // Loop through file incrementing counter
         try {
         String line = fileInput.readLine();
         while (line != null) {
         counter++;
              System.out.println("(" + counter + ") " + line);
    line = fileInput.readLine();
         numLines = counter;
    closeFile();
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile();
         System.exit(1);
    /* READ FILE */
    private void readTheFile() {
    // Open the file
    int row=0;
    int col=0;
         openFile();
    System.out.println("Read the file");     
         // Loop through file incrementing counter
         try {
    String line = fileInput.readLine();
         while (line != null)
    StringTokenizer st=new StringTokenizer(line);
    while(st.hasMoreTokens())
    data[row][col]=st.nextToken();
    System.out.println(data[row][col]);
    col++;
    row++;
    closeFile();
    catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile();
         System.exit(1);
    /* CHECK FILE NAME */
    /* Return flase if selected file is a directory, access is denied or is
    not a file name. */
    private boolean checkFileName() {
         if (fileName.exists()) {
         if (fileName.canRead()) {
              if (fileName.isFile()) return(true);
              else JOptionPane.showMessageDialog(null,
                        "ERROR 3: File is a directory");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 2: Access denied");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 1: No such file!");
         // Return
         return(false);
    /* FILE HANDLING UTILITIES */
    /* OPEN FILE */
    private void openFile() {
         try {
         // Open file
         FileReader file = new FileReader(fileName);
         fileInput = new BufferedReader(file);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File opened");
    /* CLOSE FILE */
    private void closeFile() {
    if (fileInput != null) {
         try {
              fileInput.close();
         catch (IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File closed");
    /* MAIN METHOD */
    /* MAIN METHOD */
    public static void main(String[] args) throws IOException {
         // Create instance of class FileChooser
         FileReduction1 newFile = new FileReduction1("File Reduction Program");
         // Make window vissible
         newFile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         newFile.setSize(500,400);
    newFile.setVisible(true);
    Java.lang.NullpointException
    at FileReductoin1.readTheFile <FileReduction1.java :172>
    at FileReductoin1.readFile <FileReduction1.java :110>
    at FileReductoin1.actionPerformed <FileReduction1.java :71>
    .

    1) Next time use the CODE tags. this is way too much unreadable crap.
    2) The problem is your String[][] data.... the only place I see you do anything approching initializing it is
    data = new String[numLines][];I think you want to do this..
    data = new String[numLines][3];anyway that's why it's blowing up on the line
    data[row][col]=st.nextToken();

  • Reading .txt file into char array, file not found error. (Basic IO)

    Iv been having some trouble with reading characters from a text file into a char array. I havnt been learning io for very long but i think im getting the hang of it. Reading and writing raw bytes
    and things like that. But i wanted to try using java.io.FileReader to read characters for a change and im having problems with file not found errors. here is the code.
    try
    File theFile = new File("Mr.DocumentReadMe.txt");
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);
    char buffer[] = new char[(int)theFile.length()];
    int readData = 0;
    while(readData != -1)
    readData = readMe.read(buffer);
    jEditorPane1.setText(String.valueOf(buffer));
    catch(Exception e)
    JOptionPane.showMessageDialog(null, e,
    "Error!", JOptionPane.ERROR_MESSAGE);
    The error is: java.io.FileNotFoundException: C:\Users\Kaylan\Documents\NetBeansProjects\Mr.Document\dist\Mr.DocumentReadMe.txt (The system cannot find the file specified)
    The text file is saved in the projects dist folder. I have tried saving it elsewhere and get the same error with a different pathname.
    I can use JFileChooser to get a file and read it into a char array with no problem, why doesnt it work when i specify the path manually in the code?

    Well the file clearly isn't there. Maybe it has a .txt.txt extensionthat Windows is kindly hiding from you - check its Properties.
    But:
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);You don't need all that. Just:
    FileReader readMe = new FileReader(theFile);And:
    char buffer[] = new char[(int)theFile.length()];You don't need a buffer the size of the file, this is bad practice. Use 8192 or whatever.
    while(readData != -1)
    readData = readMe.read(buffer);
    }That doesn't make sense. Read the data into the buffer and repeat until you get EOF? and do nothing with the contents of the buffer? The canonical read loop in Java goes like this:
    while ((count = in.read(buffer)) > 0)
      out.write(buffer, 0, count); // or do something else with buffer[0..count-1].
    jEditorPane1.setText(String.valueOf(buffer));Bzzt. That won't give you the content of 'buffer'. Use new String(buffer, 0, count) at least.

Maybe you are looking for

  • HT1849 how to add folder to music library on itunes 11.1

    Can some one please help me how to add a folder to music library. I can see add a file to music library option but not folder option. Thanks in Advance

  • Clearing Vendor

    Hello, I still have a problem with one vendor. In FBL1N I can see an open item, but when I try to clear it in F-44, it gives me a meesage "No open items were found". on advice from forum I have checked F110, if the vendor is not in auto-payment propo

  • Tomcat Servlet Security Problem? : Start Excel with NJAWIN - COMObjects

    I get an exception when I start my programm as servlet , as application it works just fine (when I start it as Servlet in the internal Tomcat from JBuilder it also works fine). Application app = new Application(Application.progID); // interfaces buil

  • Email alias not not receiving emails

    My friends and family are getting email bounce backs from my iCloud email alias. Help?

  • Files changed to alias

    I had a clutter of files on my desktop so, I created a folder in User>Documents called Desktop Junk and put all the files from my desktop into it. Today I tried to open one of the files and couldn't because it was now an alias and had to be fixed in