ReadFile method.

Hi,
I'm a student trying to make some java programing for an assignment. The task is to program a drawing program. Therefore I have a window class, shape classes and a main program to perform the task.
One of the task is to have a text file read by a readFile method and from that display the drawing on the screen. In other words, the text file have the attributes like rowBase, colBase etc which is read by the readFile method and resulting in a drawing.
I wrote the readFile method in my Window class. When I run it, the window (frame of the picture) is displayed but the shapes are not shown in the picture. I have pasted my readFile method below, so if anyone knows what is wrong (why my shapes are not showed in the drawing), please let me know!
public static Window readFile(String filename) throws IOException
Window newWindow;
Scanner inputStream = null;
inputStream = new Scanner(new File("T2Drawing.txt"));
int rowBase = inputStream.nextInt();
int colBase = inputStream.nextInt();
char drawingCharacter = inputStream.next().charAt(0);
inputStream.nextLine();
newWindow = new Window(rowBase, colBase, drawingCharacter);
String line = "";
line = inputStream.nextLine();
if(line.toUpperCase().equals("LINE"))
rowBase = inputStream.nextInt();
colBase = inputStream.nextInt();
int length = inputStream.nextInt();
int rowIncrement = inputStream.nextInt();
int colIncrement = inputStream.nextInt();
Line newLine = new Line(rowBase, colBase, length, rowIncrement,
colIncrement, '#');
newWindow.addShapes(newLine);
else if(line.toUpperCase().equals("CIRCLE"))
rowBase = inputStream.nextInt();
colBase = inputStream.nextInt();
int radius = inputStream.nextInt();
Circle newCircle = new Circle(rowBase, colBase, radius,'+');
newWindow.addShapes(newCircle);
else if(line.toUpperCase().equals("RECTANGLE"))
rowBase = inputStream.nextInt();
colBase = inputStream.nextInt();
int width = inputStream.nextInt();
int height = inputStream.nextInt();
Rectangle newRectangle = new Rectangle(rowBase, colBase, width,
height,'=');
newWindow.addShapes(newRectangle);
else if(line.toUpperCase().equals("TRIANGLE"))
rowBase = inputStream.nextInt();
colBase = inputStream.nextInt();
int height = inputStream.nextInt();
int rowIncrement = inputStream.nextInt();
int colIncrement = inputStream.nextInt();
Triangle newTriangle = new Triangle(rowBase, colBase, height,
rowIncrement, colIncrement, '*');
newWindow.addShapes(newTriangle);
else if (line.toUpperCase().equals("TEXT"))
rowBase = inputStream.nextInt();
colBase = inputStream.nextInt();
inputStream.nextLine();
String text = inputStream.nextLine();
int rowIncrement = inputStream.nextInt();
int colIncrement = inputStream.nextInt();
inputStream.nextLine();
Text newText = new Text(rowBase, colBase, text, rowIncrement,
colIncrement);
newWindow.addShapes(newText);
inputStream.hasNext();
return newWindow;
}

Thank you for the information about the exception! The class is called T3Main since my assignment defines it (Task 3 Main). I have tried using the code function below of my readFile method. The assignment demands me to call it readFile as well. Here is task 3's description:
"(a) To the class Window, add and implement the following static method (class method)
Window readFile(String fileName)
The method reads the text file, constructs and returns the Window object representing the drawing specified in the text fil.
(the text file is called T2Drawing.txt)
(b) Write a program, call it T3Main.java, to read the description of a drawing from a text file and display the drawing on the screen".
Here is my method again:
public static Window readFile(String filename) throws IOException
      Window newWindow;
      Scanner inputStream = null;
            inputStream = new Scanner(new File("T2Drawing.txt"));
            int rowBase = inputStream.nextInt();
            int colBase = inputStream.nextInt();
            char drawingCharacter = inputStream.next().charAt(0);
            inputStream.nextLine();
            newWindow = new Window(rowBase, colBase, drawingCharacter);
            String line = "";
            line = inputStream.nextLine();
            if(line.toUpperCase().equals("LINE"))
               rowBase = inputStream.nextInt();
               colBase = inputStream.nextInt();
               int length = inputStream.nextInt();
               int rowIncrement = inputStream.nextInt();
               int colIncrement = inputStream.nextInt();
               Line newLine = new Line(rowBase, colBase, length, rowIncrement,
               colIncrement, '#');
               newWindow.addShapes(newLine);
            else if(line.toUpperCase().equals("CIRCLE"))
               rowBase = inputStream.nextInt();
               colBase = inputStream.nextInt();
               int radius = inputStream.nextInt();
               Circle newCircle = new Circle(rowBase, colBase, radius,'+');
               newWindow.addShapes(newCircle);
            else if(line.toUpperCase().equals("RECTANGLE"))
               rowBase = inputStream.nextInt();
               colBase = inputStream.nextInt();
               int width = inputStream.nextInt();
               int height = inputStream.nextInt();
               Rectangle newRectangle = new Rectangle(rowBase, colBase, width,
                     height,'=');
               newWindow.addShapes(newRectangle);
            else if(line.toUpperCase().equals("TRIANGLE"))
               rowBase = inputStream.nextInt();
               colBase = inputStream.nextInt();
               int height = inputStream.nextInt();
               int rowIncrement = inputStream.nextInt();
               int colIncrement = inputStream.nextInt();
               Triangle newTriangle = new Triangle(rowBase, colBase, height,
                     rowIncrement, colIncrement, '*');
               newWindow.addShapes(newTriangle);
            else if (line.toUpperCase().equals("TEXT"))
               rowBase = inputStream.nextInt();
               colBase = inputStream.nextInt();
               inputStream.nextLine();
               String text = inputStream.nextLine();
               int rowIncrement = inputStream.nextInt();
               int colIncrement = inputStream.nextInt();
               inputStream.nextLine();
               Text newText = new Text(rowBase, colBase, text, rowIncrement,
                     colIncrement);
               newWindow.addShapes(newText);
               inputStream.hasNext();
               return newWindow;
        }

Similar Messages

  • Errors with a readFile method

    I wrote a method that is designed to read input from a file (readPlayers) and am getting two errors that I cannot figure out. Can you suggest why I'm getting these errors? The first error is on line 17 public void readPlayers( fin, teamArray) and reads:      Syntax error on token "(", = expected
         Syntax error on token ")", ; expected
    the second error is on line 53 else (type.equals("Hockey")) and reads Syntax error, insert ";" to complete Statement
         Syntax error, insert "AssignmentOperator ArrayInitializer" to complete ArrayInitializerAssignement
    Neither of these errors seem to fit so I'm wondering if the actual errors occur earlier in the code.??? Any help would be appreciated.
    import java.io.IOException;
    import java.util.*;
    public class TeamTwo
         private String city;
         //private String [] player;
         private static String cout;
         public static void main(String [] args) throws IOException
              Scanner fin = TFI.OpenInputFile();
              Scanner kb = new Scanner (System.in);
              int menuChoice = 0;
              public void readPlayers( fin, teamArray)
                  Player newPlayer = null;
                  int games = 0;               //basketball player
                  int timesBatted = 0;     //baseball player
                  double battingAvg = 0.0;//baseball player
                  int score = 0;               //hockey player
                  Player [] teamArray = new Player [1];
                 // String cityName = fin.nextLine();
                  if(fin.hasNext())
                        city = fin.nextLine();
                  while (fin.hasNext())
                           String type = fin.nextLine();
                           String firstName = fin.nextLine();
                           String lastName = fin.nextLine();
                           int salary = fin.nextLine();
                           fin.next();//clears buffer
                           if (type.equals("Basketball"))
                               games = fin.nextInt();
                               newPlayer = new Basketball(firstName, lastName, salary);
                           else if (type.equals("Baseball"))
                               battingAvg = fin.nextDouble();
                               timesBatted = fin.nextInt();
                               newPlayer = new Baseball(firstName, lastName, salary);
                           else (type.equals("Hockey"))
                               scoring = fin.nextInt();
                               newPlayer = new Hockey(firstName, lastName, salary);
                           fin.next();//clears buffer
                           teamArray.addPlayer( newPlayer );//call the addPlayer function
                      }//end while
              }//end readPlayers function
              

    The first error is on line 17
    public void readPlayers( fin, teamArray)When declaring a method, you have to indicate the types of the parameters, e.g., public void readPlayers(Scanner fin, Player[] teamArray) {Further, you may NEVER define a method within another method.
    the second error is on line 53
    else (type.equals("Hockey"))type.equals("...") is only for testing equality. It returns a boolean value of true or false. There are two possible solutions here:
    else if (type.equals("Hockey")) //to test if variable "type" is set to the value "Hockey"
    or
    else (type="Hockey") //to force the variable "type" to represent the string "Hockey"
    Which to use depends on what you want to accomplish.

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • How to access to a resource in the ADF application?

    Hi
    I have a jasper report file named report.jrxml in the following path in my ADF application named “app”:
    app\ViewController\src\org\nmp\app\view\report
    I wanna access to this file inside a java file located in the ViewController project as follows:
    InputStreaminSt = new FileInputStream(new File(“app\ViewController\src\org\nmp\app\view\report\report.jrxml”));
    But I get the following exception:
    java.io.FileNotFoundException: app\ViewController\src\org\nmp\app\view\report\report.jrxml (The system cannot find the path specified)
    How could I access to this resource in my application? I am using JDev 11.1.2.3
    Cheers,
    Ferez

    Timo,
    I made a test case named fileaccess and uploaded it here:
    http://rapidshare.com/files/2200118787/fileaccess.zip
    Just open the project in JDev 11.1.2.3, the Model project is empty and in the viewController project there is a single page named home.jsf in which contains a commandButton. Clicking the button executes the #{fileAccess.readFile} method. The fileAccess bean is located in org.company.fileaccess.view.beans and introduced in faces-config.xml. Body of readFile method is as the following:
    FileInputStream fis = new FileInputStream(new File("/org/company/fileaccess/view/resources/file.txt")); file.txt is located in org.company.fileaccess.view.resources and viewController project is set to copy .txt files into output directory. Clicking the button causes FileNotFoundException.
    Thank you in advance,
    Ferez

  • Cant get list of files from a folder (even though the folder and files are created with the same app)

    Ok so each character rolled with my app gets saved as an html file in a folder i create on the sdcard called RpgApp
    the code to do this is 
    private async Task saveToHtmlCharacter(string name)
    StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
    StorageFolder sdcard = (await externalDevices.GetFoldersAsync()).FirstOrDefault(); //Windows.Storage.ApplicationData.Current.LocalFolder;
    var dataFolder = await sdcard.CreateFolderAsync("RpgApp",
    CreationCollisionOption.OpenIfExists);
    var file = await dataFolder.CreateFileAsync(name+".html",
    CreationCollisionOption.ReplaceExisting);
    using (StreamWriter writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
    writer.WriteLine("<html><head><title>Character File for " + z.charNameFirst + " " + z.charNameSecond + "</title></head><body>");
    //trimed for the post
    now this as i say works perfectly and i can confirm that the files show up in the "RpgApp"folder
    now the next step is to have the app read the names of each of those html files and create a seperate button for each one named for the filename and with the filename as content (later i will link them up to load the html file they are named for in a webbrowser
    panal)
    here is the code that *should* do that
    private async Task readFiles()
    z.test.Clear();
    StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
    StorageFolder folder = (await externalDevices.GetFolderAsync("RpgApp"));
    IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
    //z.test.Add("dummy");
    foreach (StorageFile file in fileList)
    z.test.Add(file.Name);
    public async void buttonTest()
    await readFiles();
    CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
    await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    foreach (string name in z.test)
    Button button1 = new Button();
    button1.Height = 75;
    button1.Content = name;
    button1.Name = name;
    testStackPanal.Children.Add(button1);
    now i say should as what i get is an error of "A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll" (2 of them in fact one after another)
    more detailed error is at http://pastebin.com/3hBaZLQ9
    now i went through checking line after line to find the error and line that causes it is:
    StorageFolder folder = (await externalDevices.GetFolderAsync("RpgApp"));
    in the readFiles method
    i checked to make sure the case is right etc and its spot on, that IS the folder name, and remember my app creates that folder and creates the files that are inside that folder (and only files my app creates are in that folder) so it should have access
    im 100% stuck its taken me all day to get the files to save and now i cant get them to list correctly
    I have tested the button creation function with fake list data and that worked fine, as i say the error is when i tell it to look at the folder it created
    all help most greatfully recieved

    this was actually solved for me on another forum thread 
    async Task<bool> continueToReadAllFiles(StorageFolder folder)
    if (folder == null)
    return false;
    if (folder.Name.Equals("RpgApp", StringComparison.CurrentCultureIgnoreCase))
    var files = await folder.GetFilesAsync();
    foreach (var file in files)
    test.Add(file.Name);
    return false;
    var folders = await folder.GetFoldersAsync();
    foreach (var child in folders)
    if (!await continueToReadAllFiles(child))
    return false;
    return true;
    public async void buttonTest()
    test.Clear();
    StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
    var folders = await externalDevices.GetFoldersAsync();
    foreach (var folder in folders)
    if (!await continueToReadAllFiles(folder))
    break;
    //.... commented out
    ...now i say solved this is more a workaround...but it works.
    I would love to know why we cant just scan the RpgApp folder instead of having to scan the whole dc card and disregard all thats not in the RpgApp folder

  • What is the best practise to provide a text file for a Java class in a OSGi bundle in CQ?

    This is probably a very basic question so please bear with me.
    What is the best way to provide a .txt file to be read by a Java class in a OSGi bundle in CQ 5.5?
    I have been able to read a file called "test.txt" that I put in a structure like this /src/resources/<any-sub-folder>/test.txt  from my java class  at /src/main/java/com/test/mytest/Test.java using the bundle's getResource and getEntry calls but I was not able to use the context.getDataFile. How is this getDataFile method call to be used?
    And what if I want to read the file located in another bundle, is it possible? or can I add the file to some repository and then access it - but I am not clear how to do this.
    And I would also like to know what is the best practise if I need to provide a large  data set in a flat file to be read by a Java class in CQ5.
    Please provide detailed steps or point me to a how to guide or other helpful resources as I am a novice.
    Thank you in advance for your time and help.
    VS

    As you can read in the OSGi Core specification (section 4.5.2), the getDataFile() method is to read/write a file in the bundle's private persistent area. It cannot be used to read files contained in the bundle. The issue Sham mentions refers to a version of Felix which is not used in CQ.
    The methods you mentioned (getResource and getEntry) are appropriate for reading files contained in a bundle.
    Reading a file from the repository is done using the JCR API. You can see a blueprint for how to do this by looking at the readFile method in http://svn.apache.org/repos/asf/jackrabbit/tags/2.4.0/jackrabbit-jcr-commons/src/main/java /org/apache/jackrabbit/commons/JcrUtils.java. Unfortunately, this method is not currently usable as it was declared incorrectly (should be a static method, but is an instance method).
    Regards,
    Justin

  • Need help fast about opening file

    hello i have this 2 classes to open file and display it .the open method works fine but when ever i try to open different file it adds the new data and display both . the problem is it not suppose to add the new data to the old list it should only show the new data only ...can any one help thx
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class RoomGUI extends JFrame
       private RoomSortedList list;
         // Menu items:
       private JMenuItem mOpen;
       private JMenuItem mSaveAs;
       private JMenuItem mExit;
         // Displayed regions of the window:
         private JTextField messageField;
         private JTextArea textArea;
          * Constructor for RoomGUI object to set up
          * GUI window with menu.
         public RoomGUI()
              list=new RoomSortedList();     
         // Components to display on window:
              messageField = new JTextField();
              messageField.setEditable(false);
              textArea = new JTextArea();
              textArea.setEditable(false); 
                        // Arrnge components on window:
              Container contentPane = getContentPane();
              contentPane.add(messageField, BorderLayout.SOUTH);
              JPanel centerPanel = new JPanel();
              contentPane.add(centerPanel, BorderLayout.CENTER);
              centerPanel.setLayout(new GridLayout(1,1));
              centerPanel.add(new JScrollPane(textArea));
    //  Create menu items for the "File" menu:
          mOpen = new JMenuItem ("Open");
          mSaveAs = new JMenuItem ("SaveAs");
          mExit = new JMenuItem ("Exit");
          //  Create "File" menu:
          JMenu fileMenu = new JMenu ("File", /*tearoff =*/ false);
          fileMenu.add(mOpen);
          fileMenu.add(mSaveAs);
          fileMenu.add(mExit);
          // Create menu bar:
          JMenuBar mainMenuBar = new JMenuBar();
          mainMenuBar.add(fileMenu);
          // Put menu bar on this window:
          setJMenuBar(mainMenuBar);
         mOpen.addActionListener( new FileOpener(textArea,list) );
         mSaveAs.addActionListener( new FileSaver(list) );
          mExit.addActionListener(new Quitter());
              // Routine necessities with JFrame windows:
              setSize(500, 400);
              setLocation(200, 100);
              setTitle("Project 4");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setVisible(true);
         } // constructorfile opener
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FileOpener implements ActionListener
         private RoomSortedList list;
         private JTextArea textArea=new JTextArea();
              private int returnvalue;
              private String filename;
              private JTextField messageField;
         public FileOpener(JTextArea ta,RoomSortedList ls)
              this.textArea=ta;
              this.list=ls;
         public void actionPerformed(ActionEvent e)
              list =new RoomSortedList();
              messageField = new JTextField();
              JFileChooser filechooser = new JFileChooser();
             // if a file is selected returnvalue = 0
             // else if cancel button is pressed
             // returnvalue = 1
             returnvalue = filechooser.showOpenDialog(null);
             //if open is selected then return filename
             if (returnvalue == filechooser.APPROVE_OPTION){
                filename = filechooser.getSelectedFile().toString();
                // now read the rooms from the file with the name filename
                // invoke the readfile method
                readFile(filename);
                messageField.setText(filename);
             }//if
             // if cancel is selected then close the filechooser
             else if (returnvalue == filechooser.CANCEL_OPTION)
                filechooser.cancelSelection();
       * Reads room data from a text file.Check if each lines are in valid room
       * format, and values. Catches exception errors for any invalid lines or
       * values thrown by ParseRoom or Room constructors.
       * Valid lines are appended to an sorted linked list. 
       * @param filename     name of file containing
       private void readFile(String filename)
           JFrame errorD=new JFrame();
          String str=null;
          Room r=null;
          int linenum=0;
          TextFileInput Obj=null;
          try
             Obj = new TextFileInput(filename);
          catch (RuntimeException rte)
             System.out.println(rte.getMessage());
          while (true)
             str = Obj.readLine();
             linenum++;
             if (str==null) break; // to stop reading lines at the end of file
             try
                r = RoomTextFormat.parseRoom(str);
             catch (RoomTextFormatException rtf)
                JOptionPane.showMessageDialog(errorD, "Error reading line # " +
                   linenum + ": " + str + "\n" + rtf.getMessage() + "\n"+
                   "This line of text has been excluded from the list.",
                   "Text Format Error", JOptionPane.ERROR_MESSAGE);
                continue;
             catch (IllegalRoomException ire)
                JOptionPane.showMessageDialog(errorD, "Error reading line # " +
                   linenum + ": " + str + "\n" + ire.getMessage() + "\n" +
                   "This line of text has been excluded from the list.",
                   "Room Instantiation Error", JOptionPane.ERROR_MESSAGE);
                continue;
             list.insert (r);
             textArea.setText("");
                RoomListIterator MyIterator = list.beginIterating();
                int c=1;
                while (MyIterator.hasNext())
                   Room m = MyIterator.next();
                   textArea.append(c + ": " + m + "\n");
                   c++;
                }//while
          }// while (true)
       } // readFile()
    }

    i apologize again.thx anyway . heres the code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class RoomGUI extends JFrame
         private RoomSortedList list;
         // Menu items:
         private JMenuItem mOpen;\
         // Displayed regions of the window:
         private JTextField messageField;
         private JTextArea textArea;
          * Constructor for RoomGUI object to set up
          * GUI window with menu.
         public RoomGUI()
              list=new RoomSortedList();     
              // Components to display on window:
              messageField = new JTextField();
              messageField.setEditable(false);
              textArea = new JTextArea();
              textArea.setEditable(false); 
              // Arrnge components on window:
              Container contentPane = getContentPane();
              contentPane.add(messageField, BorderLayout.SOUTH);
              JPanel centerPanel = new JPanel();
              contentPane.add(centerPanel, BorderLayout.CENTER);
              centerPanel.setLayout(new GridLayout(1,1));
              centerPanel.add(new JScrollPane(textArea));
                  //Create menu items for the "File" menu:
              mOpen = new JMenuItem ("Open");
              //  Create "File" menu:
              JMenu fileMenu = new JMenu ("File", /*tearoff =*/ false);
              fileMenu.add(mOpen);
              // Create menu bar:
              JMenuBar mainMenuBar = new JMenuBar();
              mainMenuBar.add(fileMenu);
              // Put menu bar on this window:
              setJMenuBar(mainMenuBar);
              mOpen.addActionListener( new FileOpener(textArea,list) );
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setVisible(true);
         } // constructor
    } // class RoomGUIopen file
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FileOpener implements ActionListener
         private RoomSortedList list;
         private JTextArea textArea=new JTextArea();
              private int returnvalue;
              private String filename;
              private JTextField messageField;
         public FileOpener(JTextArea ta,RoomSortedList ls)
              this.textArea=ta;
              this.list=ls;
         public void actionPerformed(ActionEvent e)
              list =new RoomSortedList();
              messageField = new JTextField();
              JFileChooser filechooser = new JFileChooser();
             // if a file is selected returnvalue = 0
             // else if cancel button is pressed
             // returnvalue = 1
             returnvalue = filechooser.showOpenDialog(null);
             //if open is selected then return filename
             if (returnvalue == filechooser.APPROVE_OPTION){
                filename = filechooser.getSelectedFile().toString();
                readFile(filename);
                messageField.setText(filename);
             }//if
             // if cancel is selected then close the filechooser
             else if (returnvalue == filechooser.CANCEL_OPTION)
                filechooser.cancelSelection();
       private void readFile(String filename)
          String str=null;
          TextFileInput Obj=null;
             Obj = new TextFileInput(filename);
          while (true)
             str = Obj.readLine(); // 
             if (str==null) break; // to stop reading lines at the end of file
             list.insert (str);
             textArea.setText("");
                RoomListIterator MyIterator = list.beginIterating();
                int c=1;
                while (MyIterator.hasNext())
                   Room m = MyIterator.next();
                   textArea.append(c + ": " + m + "\n");
                   c++;
                }//while
          }// while (true)
       } // readFile()
    }

  • Error Compiliing:symbol  : class TextFileInput

    Greetings,
    I have two computers with the java compiler installed. On one, the program works perfect. On the other computer, it doent.
    Here is the error message I get when I compile the program:
    symbol : class TextFileInput
    location: class Project1
              TextFileInput dataFile = new TextFileInput(f);
    ^
    C:\cs212\Project1.java:66: cannot find symbol
    symbol : class TextFileInput
    location: class Project1
              TextFileInput dataFile = new TextFileInput(f);
    ^
    2 errors
    Tool completed with exit code 1
    The program works fine on the other computer. I have the same compiler version installed on both computers. I tried making changes to the class path but doesnt seem to work. What should I do. Please help
    Below is the code of my program:
    public class Project1
         * Main method.
         * @param args command-line arguments - inputFile.txt needed
         public static void main(String[] args)
              String filename      = args[0];
    final int ELEMENTS      = 10;
              String[] namesArray = new String[ELEMENTS];
              String[] speciesArray = new String[ELEMENTS];
              int     [] ageArray = new int [ELEMENTS];
              if (args.length != 1)
                   System.out.println("You have entered wrong "
                   + "argument information. Exiting the system");
              System.exit(0);
         }//end if args.length != 1
              int arraySize = readFile(args[0],speciesArray, namesArray, ageArray);
              displayResults(speciesArray, namesArray, ageArray, arraySize);
              sort(speciesArray, namesArray, ageArray, arraySize);
              displayResults(speciesArray, namesArray, ageArray, arraySize);
    }// end main
         * readfile method.- Read data from inputFile.txt and place
         * it into Arrays
         * @param f - the name of the file - inputFile.txt
         * @param sp - speciesArray - Array that contains the species
         * @param na - nameArray - Array that contains the animal names
         * @param a - ageArray - Array that contains animal age
         * @return - the size of the array to a variable called arraySize
         public static int readFile(String f, String[] sp, String[] na, int[] a)
              TextFileInput dataFile = new TextFileInput(f);
    //final String lineBreak = System.getProperty("line.separator");
              // Input the first line from the file:
         String line      = dataFile.readLine();
         int lengthFilled      = 0;
              // Read the content of the file and place it in a string of arrays
              while (line != null )
                   StringTokenizer st = new StringTokenizer(line, "|");
                   String species = st.nextToken();
                   String name = st.nextToken();
                   int age = Integer.parseInt(st.nextToken());
                   boolean validate = isValidSpecies(species);
    if (validate != true)
                        System.out.println("The line: \""+ line + "\""+ " in the file is not valid");
                   System.out.println("It will not be included in the array");
                   line = dataFile.readLine();
              else
                        sp[lengthFilled] = species;
                        na[lengthFilled] = name;
                        a [lengthFilled] = age;
                        lengthFilled++;
                   line                = dataFile.readLine();
              }//end else
              }// end while loop
         dataFile.close();
              return lengthFilled;
         }//end readFile
         * isValidSpecies method. - Makes sure the species is either a CAT or DOG
         * @param s - the species value of the array at xxx position
         * @return - it will return true if the species name is either CAT or DOG
         * - else it will return false.
         public static boolean isValidSpecies(String s)
              if ( (s.compareTo("DOG") == 0) || (s.compareTo("CAT") == 0))
              return true;
         else
              return false;
    }//end isValidSpecies
    * sort method. - It sorts the array based on name.
    * @param sp - speciesArray - Array that contains the species
    * @param na - nameArray - Array that contains the animal names
    * @param a - ageArray - Array that contains animal age
    * @param length - the size of the partially filled array
         public static void sort(String[] sp, String[] na, int[] a, int length)
              //Sort the array using selection sort array.
              for (int i = 0; i < length; i++)
                   // Find the lowest-valued element in
                   // the subarray from index i up to
                   // index length - 1
                   int indexLowest = i;
                   for (int j = i + 1; j < length; j++)
                        if ( na.compareTo(na[indexLowest]) <= 0 )
                             indexLowest = j;
                        // Put the lowest-valued element at
                   // index i, swapping if necessary:
                        if ( na[indexLowest].compareTo(na[i]) <= 0 )
                             String tempName = na[indexLowest];
                             String tempSpecie = sp[indexLowest];
                             int tempnumb = a [indexLowest];
                             na[indexLowest] = na[i];
                             sp[indexLowest] = sp[i];
                             a [indexLowest] = a [i];
                             na[i] = tempName;
                        sp[i] = tempSpecie;
                             a [i]           = tempnumb;
                        }//end if
    }//for loop
         }//for loop
    }//end sort method
    * displayResults method. - Display the info from the arrays to a JOptionPane.
    * @param sp - speciesArray - Array that contains the species
    * @param na - nameArray - Array that contains the names
    * @param a - ageArray - Array that contains animal age
    * @param length - the size of the partially filled array
         public static void displayResults(String[] sp, String[] na, int[] a, int length)
              JTextArea textArea = new JTextArea();
         textArea.setEditable(false);
         final String lineBreak = System.getProperty("line.separator");
              for (int i = 0; i < length; i++)
              textArea.append(sp[i] + " " + na[i] + " " + a[i] + lineBreak);
              JOptionPane.showMessageDialog(null, textArea);
    }// end displayResults
    }//end class Project1

    How could that be, that the class TexFileinput is
    missing. The installation of java, I believe version
    1.5.0_04 was done at the same time on both machines.That class is one of your classes. It's not part of Java. Look for it.
    Anyway, the classpath seem to be the same?
    I know the path is the same on both computers, but I
    dont know where to check for the class path.Type echo %classpath% at a cmd prompt.
    Thanks alot for your prompt response!!!!

  • Remove words from file

    Hello, I have created a class which is supposed to be an array of stopwords (words that I want to remove from a file).
    Then I want to create another class which reads in a file. It reads the file. Then it looks through the array of stopwords. If it encounters a word in the file which is the same as the word in the array, it replaces it with nothing.
    I want this class to be separate from the main class so that in the main class,I can specify any file, and the stopwords will be removed. Here is some code, thanks
    import java.io.*;
    import java.util.*;
    public class StopWordArray {
         //This class represents an array of stopwords
         //The stopwords are read from a text file into an array
         private String [] tokens;
         //constructor
        public StopWordArray(){          
             try{
    //         open input stream
             File inputFile = new File("/home/myrmen/workspace/Chisquare/extract/stopWordList.txt");
             InputStream inStream = new FileInputStream(inputFile);
             InputStreamReader inreader = new InputStreamReader(inStream, "8859_1");
             BufferedReader reader = new BufferedReader(inreader);
            String line;
            //Fills array
            while ((line = reader.readLine()) != null) {
            StringTokenizer st1 = new StringTokenizer(line);
            int numberOfElements = st1.countTokens();
             tokens = new String[ numberOfElements ];
            int index = 0;
             while( st1.hasMoreTokens() )
               String element = st1.nextToken();
             tokens[ index ] = element;
                       index ++;
            reader.close();
           catch (Exception ex) { ex.printStackTrace(); }
    import java.io.*;
    import java.util.StringTokenizer;
    public class RemoveStop {
         //Fields
         private StopWordArray myArray = new StopWordArray();
        private String myString;
         //Constructor
        public RemoveStop(String myString){
    import java.io.*;
    public class Main {
         public static void main(String[] args) {
              StopWordArray theWords = new StopWordArray();
            theWords.printArray();
            String file = "/home/myrmen/workspace/Chisquare/extract/Turing";
            RemoveStop remove = new RemoveStop(file);
    }

    Ok, here is an update:
    private String [] tokens;
       //Method which returns each element in the array as a string
        public String word()
        String word = null;
        for(int i = 0; i < tokens.length; i++)
        word = tokens.toString();     
    return word;
    public void readFile(){
    String output = null;
    StringTokenizer st1 = new StringTokenizer(aString);
    while(st1.hasMoreTokens())
    String element = st1.nextToken();     
    //System.out.println(myArray.word());
    if(element.equals(myArray.word()))
    output = element.replaceAll(myArray.word(), "WAY");
    //else{System.out.println("ERROR");
    System.out.println(output);
    But with the readFile() method, I only access the LAST element of the array. How can I iterate through the whole array, and search for the words that are stored in the array in the input file?

  • How to start with a gui

    Hi,
    i have a program that works fine, at the moment it just outputs results to the screen.
    I'm required to create a gui for this but really don't know where to start.
    i have a Test class which has a main method in it which calls all the other classes.
    my main class is below:
    public class Test
         public static void main(String[] args)
              Data d = new Data();
              Vector data = d.readFile("File9.txt");
              /*normalise the data and store in vector (outerVetor)*/
              Normalise rf = new Normalise();
              Vector dataNormalised = rf.normalise(data);
              datasize = dataNormalised.size();
              Affinity af = new Affinity();
              Vector affinity = af.calcAffinity(dataNormalised);
              Initialise i = new Initialise();
              i.setSeed(1);
              seed = i.getSeed();
              i.setHypermutationRate(2.0);
              hypermutationRate = i.getHypermutationRate();
              i.setClonalRate(10.0);
              clonalRate = i.getClonalRate();
              i.setTotalResources(15.0);
              totalResources = i.getTotalResources();
              i.setStimulationValue(0.99);
              stimulationValue = i.getStimulationValue();
              i.setAffinityThresholdScalar(0.2);
              affinityThresholdScalar = i.getAffinityThresholdScalar();
              i.setKNN(4.0);
              KNN = i.getKNN();
              Vector MemoryPool = i.seedMemoryPool(dataNormalised, seed);
              Float affinityThreshold = i.affinityThreshold(affinity);
              Stimulation s = new Stimulation();
              Training t = new Training();
              CompetitionForLtdRes c = new CompetitionForLtdRes();
              MemoryCellSelection MS = new MemoryCellSelection();
              Classification C = new Classification();
              for(int k=0;k<dataNormalised.size();k++)
                   Antigen = (Vector)dataNormalised.elementAt(k);
                   if(memPoolStimulation.floatValue() == zero.floatValue())
                        MemoryPool.add(Antigen);
                   else
                   stimIndex = s.getStimIndex();
                   Vector ARB =t.ARBGeneration(BestMatch,hypermutationRate,clonalRate);
               Vector Candidate = c.runARBRefinement(ARB, Antigen, maxDist,stimulationValue,clonalRate, totalResources);
              MemPoolsize = MemoryPool.size();
              reduction = 100 - ((double)MemPoolsize/datasize*100);
              Antigen1 = (Vector)dataNormalised.elementAt(1);
              Float classify = C.KNN(MemoryPool,Antigen1, KNN, maxDist);
    }I really don't know where to start with this. i know i need a fileDialog to select whic file to use at the start and a scrollable pane to display trhe results but really don't know where to begin.
    can anybody offer some help or point me in the right dircection?
    Cheers

    Hi,
    I've managed to open a file using the file dialog.
    I'm trying to noe perform an action with this file. I have a class called Data which reads in a file and reads each line of the file into a vector. so i have a vector of vectors at the end where the inner vectors are the lines of the file.
    I'm unsure of how to call this class using the selected file.
    ultimately this is the kind of thing i'm going to need to do through out.
    i have created an instance of the class Data and trie to call the method using the file but getting the following error:
    RunPanel.java:59: readFile(java.lang.String) in Data cannot be applied to (java.io.File)
    Vector data = d.readFile(file);
    my code is:
    public class RunPanel extends JPanel implements ActionListener
         JButton openButton;
         JTextArea log;
             JFileChooser fc;
         //cretaed an instance of Data class to use later on
         Data d = new Data();
    public void actionPerformed(ActionEvent e) {
            //Handle open button action.
            if (e.getSource() == openButton) {
                int returnVal = fc.showOpenDialog(RunPanel.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //This is where a real application would open the file.
                    log.append("Opening: " + file.getName() + "." + newline);
              //trying to call the readfile method in Data class here
              Vector data = d.readFile(file);
                } else {
                    log.append("Open command cancelled by user." + newline);
                log.setCaretPosition(log.getDocument().getLength());
        }can anybody explain what's going on here?
    Cheers

  • How to use user defined exception class

    Hi all
    I just need som help with creating a user defined exception class.
    Im writing a small/simple text editor.
    My exception class looks like this:
    public class myExcp extends Throwable
         private String message;
         public myExcep(String message)
              this.message = message;
         public void display()
              System.out.println(message);
    I would like to use it when a user tries to open a exe-file instead of a txt file.
    Here is some code from the editor:
    if (e.getSource() == open)
    saveOld();
    if (fc.showOpenDialog(null)== JFileChooser.APPROVE_OPTION)
    readFile(fc.getSelectedFile().getAbsolutePath());           
    saveas.setEnabled(true);                
    So, should I use exception here or at the readFile method?
    readfile:
    private void readFile(String fileName)
    try
    String tmp = fileName.substring(fileName.length() -4, fileName.length());
    if (!tmp.equals(".exe"))
    FileReader r = new FileReader(fileName);
    textarea.read(r, null);
    r.close();
    currentFile = fileName;
    label.setText(currentFile);
    changed = false;
    catch (IOException e)
    JOptionPane.showMessageDialog (this, "Cannot find the file " + fileName);
    Where and how do I use my exception class.
    Do I need to create an instance? Where?
    Should the exception class extend Exception instead?
    Thank you in advance /

    Extend Exception, not Throwable. It's a checked exception that way.
    Follow the Sun coding standards and make that exception class name start with a capital letter.
    When you extend Exception, override all four ctors.
    What's that display method you added? Isn't getMessage() good enough?
    You need to create a new instance just before you throw the exception, of course.
    Sounds like a terrible design, by the way. Exceptions shouldn't be used like "go to" for app logic. They should signal unrecoverable conditions. You can easily recover from the situation you've described simply by displaying a pop-up that tells the user to open only text-readable file types. I think that's a better solution.
    %

  • Using textarea to write data to html files

    Hi. I am trying to make an application to change contents of html files. I used filereader and filewriter constructors but I guess I have a problem with using textarea. I want the data from the file to appear in a textarea so I can edit it and save.
    boolean saveFile () {
    JTextArea textarea = new JTextArea();
    JFrame frame = new JFrame();
    frame.add(textarea);
    File file = null;
    File fFile = new File ("default.java");
    JFileChooser fc = new JFileChooser ();
    htmlFilter fhtmlFilter = new htmlFilter();
    // Start in current directory
    fc.setCurrentDirectory (new File ("."));
    // Set filter for Java source files.
    fc.setFileFilter (fhtmlFilter);
    // Set to a default name for save.
    fc.setSelectedFile (fFile);
    // Open chooser dialog
    int result = fc.showSaveDialog (this);
    if (result == JFileChooser.CANCEL_OPTION) {
    return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
    fFile = fc.getSelectedFile ();
    return writeFile (file,textarea.getText);
    return true;
    // saveFile
    boolean openFile () {
    htmlFilter fhtmlFilter= new htmlFilter();
    File file = new File("");
    JTextArea textarea = new JTextArea();
    JFileChooser fc = new JFileChooser ();
    fc.setDialogTitle ("Open File");
    // Choose only files, not directories
    fc.setFileSelectionMode ( JFileChooser.FILES_ONLY);
    // Start in current directory
    fc.setCurrentDirectory (new File ("."));
    // Set filter for Java source files.
    fc.setFileFilter (fhtmlFilter);
    // Now open chooser
    int result = fc.showOpenDialog (this);
    if (result == JFileChooser.CANCEL_OPTION) {
    return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
    file = fc.getSelectedFile ();
    JFrame frame= new JFrame();
    frame.add(textarea);
    frame.pack();
    frame.setVisible(true);
    // Invoke the readFile method in this class
    return writeFile (file, textarea.getText ());
    return true;
    } // openFile
    public static boolean writeFile (File file, String dataString) {
    try {
    PrintWriter out =
    new PrintWriter (new BufferedWriter (new FileWriter (file)));
    out.print (dataString);
    out.flush ();
    out.close ();
    catch (IOException e) {
    return true;
    } // writeFile
    public String readFile(File file)
    JFrame frame= new JFrame();
    JTextArea textarea = new JTextArea();
    frame.add(textarea);
    StringBuffer contents = new StringBuffer();
    //declared here only to make visible to finally clause
    BufferedReader input = null;
    try {
    //use buffering, reading one line at a time
    //FileReader always assumes default encoding is OK!
    input = new BufferedReader( new FileReader(file) );
    String line; //not declared within while loop
    * readLine is a bit quirky :
    * it returns the content of a line MINUS the newline.
    * it returns null only for the END of the stream.
    * it returns an empty String if two newlines appear in a row.
    while (( line = input.readLine()) != null){
    System.out.println(line);
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    catch (IOException ex){
    ex.printStackTrace();
    finally {
    try {
    if (input!= null) {
    //flush and close both "input" and its underlying FileReader
    input.close();
    catch (IOException ex) {
    ex.printStackTrace();
    return contents.toString();
    }

    Sorry this didn't get a response sooner. You can alter the way your consumer loop writes the data to file by altering the data that you send through the queue. I would suggest clustering your data (the array you currently send) with an array of booleans. Then you can unbundle this cluster in the consumer loop before you write to file and use it accordingly. This should allow you to do what you're trying to do.
    Just to give you some feedback on your code, there are few things that you can improve upon. I'm sure this is a learning process so you probably know a lot more about LabVIEW now than you did when you started.
    All of your array operations in there can be done much simpler. You have a whole Index Array node that inputs 8-21 in order. This can be done by simply having an 8 at the beginning and dragging the rest down since the indices always count from the previous by default. You are also doing a lot of indexing and re-building of arrays. You should look int o Array Subset VI  and Array To Cluster node to consolidate here.
    You have a lot of indicators and controls that coudl be consolidated in to array and/or clusters. Your "element 1", "element 2", etc  indicators are all displayed on the front panel next to each other, so why not just display them as an array?
    You use property nodes in a couple places to read the values. This can be better done by a local variable. Property nodes shouldn't usually be read from continuously.

  • Question on Files and Exceptions

    Hi everyone.
    I have a program that is supposed to let you use a JFileSearcher to find a text file, enter some search terms into a JTextArea and when you click a button it opens a new frame. The new frame is it's own class and its constructor requires a file object and an array of Strings. The problem I have is that it isn't reading the file right. I put my readFile() method inside a try clause as well as my Scanner object definition. But, for some reason an exception keeps getting thrown when it tries to execute the readFile() method, which obviously makes the rest of my program not work. Here's my code:
    FileSearcher.java
    * FileSearcher.java
    * Darren Gordon
    * @version 1.00 2008/10/18
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class FileSearcher extends JPanel implements ActionListener {
         private JButton find, results, clear;
         private JLabel lblTitle, lblFilePath, lblSearchTerms;
         private JTextField filePath;
         private JTextArea searchTerms;
         private JFileChooser finder;
         private File file;
         private boolean pickedFile = false;
         public static void main(String[] args) {
              new FileSearcher();
        public FileSearcher() {
             JFrame f = new JFrame("D-Train's String File-Searcher, preferred Edition");
             f.setSize(350, 300);
             f.setResizable(false);
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             makePanel();     
             f.add(this);
             f.setVisible(true);
        public void makePanel() {
             try {
                  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
             } catch(Exception e) {
             JPanel top = new JPanel();
             lblTitle = new JLabel("String File-Searcher");
             lblFilePath = new JLabel("Chosen File:");
             filePath = new JTextField(30);
             find = new JButton("Find File");
             JPanel center = new JPanel();
             results = new JButton("Get Results");
             clear = new JButton("Clear Fields");
             lblSearchTerms = new JLabel("Search Terms - seperate with a semi-colon(;)");
             searchTerms = new JTextArea(5, 35);
             finder = new JFileChooser();
             find.addActionListener(this);
             results.addActionListener(this);
             clear.addActionListener(this);
             top.add(lblTitle);
             top.add(lblFilePath);
             top.add(filePath);
             top.add(find);
             top.setPreferredSize(new Dimension(300, 50));
             center.add(lblSearchTerms);
             center.add(searchTerms);
             center.add(results);
             center.add(clear);
             setLayout(new BorderLayout(5, 5));
             add(BorderLayout.NORTH, top);
             add(BorderLayout.CENTER, center);
        public String[] getSearchTerms() {
             String[] temp = searchTerms.getText().split(";");
             return temp;
        public void actionPerformed(ActionEvent e) {
             if(e.getSource() == find) {
                  int temp = finder.showOpenDialog(this);
                  if(temp == finder.APPROVE_OPTION) {
                       file = finder.getSelectedFile();
                       pickedFile = true;
                       filePath.setText(file.getAbsolutePath());     
             } else if(e.getSource() == clear) {
                  searchTerms.setText("");
             } else if(e.getSource() == results && pickedFile) {
                  new Results(file, getSearchTerms());
    }Results.java
    * @(#)Results.java
    * Darren Gordon
    * @version 1.00 2008/10/18
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class Results extends JPanel {
         private Scanner scan;
         private File file;
         private String[] document, searchTerms;
         private int[] wordsCount;
         private int counter = 0;
         private JLabel lblTitle;
         private JTextArea resultsBox;
         private JScrollPane scroll;
        public Results(File a, String[] s) {
             JFrame f = new JFrame("Search Results");
             f.setResizable(false);
             f.setSize(350, 200);
             searchTerms = s;
             wordsCount = new int[searchTerms.length];
             Arrays.fill(wordsCount, 0);
             file = a;
             try {
                  readFile();
             } catch(Exception e) {
                  System.out.println("File cannot be read.");
             makePanel();
             findResults();
             giveResults();
             f.add(this);
             f.setVisible(true);
        private void readFile() {
             try {
                  scan = new Scanner(file);
             } catch(Exception e) {
                  System.out.println("Unable to scan file.");
             while(scan.hasNextLine()) {
                  document[counter] = scan.nextLine();
                  counter++;
        private void findResults() {
             for(int i = 0; i < searchTerms.length; i++) {
                  for(int j = 0; j < counter; j++) {
                        wordsCount[i] = countOccurances(document[j], searchTerms);
    private int countOccurances(String line, String search) {
         boolean searching = true;
         int count = 0;
         int index = 0;
         while(searching) {
              index = line.indexOf(search);
              if(index == -1) {
                   searching = false;
              } else {
                   count++;
                   line = line.substring(index + search.length());
         return count;
    private void giveResults() {
         for(int i = 0; i < searchTerms.length; i++) {
              if(wordsCount[i] > 0) {
                   resultsBox.append("Search term " + searchTerms[i] + " appeared " + Integer.toString(wordsCount[i]) + " time(s).\n");
         resultsBox.append("\nThe rest of the search terms turned up no results.");
    private void makePanel() {
         try {     
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         } catch(Exception e) {
         lblTitle = new JLabel("Search Results");
         resultsBox = new JTextArea(5, 30);
         resultsBox.setLineWrap(true);
         scroll = new JScrollPane(resultsBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         add(lblTitle);
         add(scroll);
    }Any ideas why it won't run readFile()?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Ok, basic Exception handling:
    Never throw away useful information.
    You've got some empty catch blocks: Very, very bad!
    You've got some catch blocks that only print a generic message: Bad.
    Add at least "e.printStackTrace()" to every catch block.
    Then you will see exactly which error occurs and where it happend. That information helps a lot (hint: post it!).

  • Display 3D characters?

    Suppose that i already got the 3DS Max charater. How do i display him.?
    Please show me some sample source codes.

    To write an .ASE loader begin with this:
    protected void load (String path) throws IOException {
        location     = new URL(path);
        loaderStream = new BufferedInputStream(location.openStream());;
        reader       = new BufferedReader(new InputStreamReader(loaderStream));
        parser       = new StreamTokenizer(reader);
        parser.eolIsSignificant(false);
        parser.wordChars('_', '_');
        parser.wordChars('*', '*');
        parser.whitespaceChars(':', ':');
        System.err.println("Reading: " + path);
        readFile();
        convertModel();
        loaderStream.close();
    }Specify the methods by yourself. The readFile() method must create arrays containing coodinates, normals, texture coords.
    To read a coordinate:
    private Point3f getVertexPoint() {
    //returns a Point3f with one set of vertex coordinates (each point for a single vertex)
    Point3f point = new Point3f();
    for( ; ; getToken()) {
    if((String)parser.sval != null) {   
    //READS POINT COORDINATES
    if(((String)parser.sval).equals("*MESH_VERTEX")) {
    getToken();
    //Reads vertex number.
    getToken();
    point.x = (float)parser.nval;
    getToken();   
    point.z = -(float)parser.nval;
    getToken();
    point.y = (float)parser.nval;       
    return point;

  • Writing file

    Hi,
    I'm trying to write a program that would read a directory of text files and then write it to a file. So far, this program can read correcty, (well, except for sub-directories). I try to write it to a file by creating a filewriter object but it doesn't work - the file would be empty - I would appreciate any help in solving this.
    import java.io.*;
    public class ListTest
    public ListTest()
    file = new File("temp");
    fileList = file.list();
    System.out.print("Files in " + file.getName() + " are ");
    for(int i = 0; i < fileList.length; i++)
    fileList[i] = file + "\\" + fileList;
    System.out.print(fileList[i] + " ");
    public void readFile()
    for(int i = 0; i < fileList.length; i++)
    try
    FileReader filereader = new FileReader(fileList[i]);
    int j;
    while((j = filereader.read()) != -1)
    System.out.print((char)j);
    filereader.close();
    catch(FileNotFoundException filenotfoundexception)
    System.out.println(filenotfoundexception);
    return;
    catch(IOException ioexception)
    System.out.println(ioexception);
    public static void main(String args[])
    ListTest listtest = new ListTest();
    listtest.readFile();
    File file;
    String fileList[];

    I'm not sure what you are attempting to do but here is my assumption.
    You are trying to write to a file the names of all the files in a directory that are text files, denoted by a .txt file extension.
    The code you have submitted is unlikely to compile because you overight a String array with a String
    Other errors are:
    1. You don't index into arrays when you iterate around them.
    2. You close the FileReader in the readFile method in the while loop which would cause an exception to be thrown after executing the loop once.
    3. You never write to a file.
    Hope this helps.

Maybe you are looking for