OutputStream closes FileReader

Hi all,
I've been doing some tests about concurrent file access and i've found something that i don't understand..
I've implementet two thread-extended classes, one that accesses a file via FileInputStream and reads it's content, and another one that writes into the same file via FileOutputStream (while the reader thread is still reading the file).
If I start some reader threads them begin reading the file ok, but when the writter thread starts and accesses the same file, every reader thread stops because of a suddenly EOF found.
This means that FileReader doesn't lock the files it accesses? Should it be the right behavior? I mean, wouldn't be safer that a FileOutputStream were not able to access a file that is been already accessed by a FileInputStream?
This is the code that I used for testing:
package iotests;
import java.io.FileOutputStream;
public class IOTWriterThread extends Thread {
     private String filename;
     private int iterations;
     private int waitTime; //millis that the thread will wait every time that write a byte
     private String threadId;
     public IOTWriterThread(String pFn, int pI, int pWT){
          this.filename = pFn;
          this.iterations = pI;
          this.waitTime = pWT;
          this.threadId = Long.toString(System.currentTimeMillis());
     public void run(){
          FileOutputStream fos = null;
          try{
               fos = new FileOutputStream(this.filename);
               for(int i=0;i<this.iterations;i++){
                    fos.write(65); //write 'A' char
                    System.out.println("{writter["+this.threadId+"]/iteration["+i+"]}");
                    Thread.sleep((long)this.waitTime);
               System.out.println("{writter["+this.threadId+"]/end of writting.}");
          }catch(Exception ex){
               System.out.println("Exception writting file ["+this.filename+"].");
          }finally{
               this.closeFOS(fos);
               fos = null;               
     private void closeFOS(FileOutputStream pFos){
          if(pFos != null){
               try{
                    pFos.close();
               }catch(Exception e){
                    e.printStackTrace();
package iotests;
import java.io.FileInputStream;
public class IOTReaderThread extends Thread {
     private String filename;
     private String threadId;
     private int waitTime; //millis that the thread will wait every time that read a byte
     public IOTReaderThread(String pFn, int pWT){
          this.filename = pFn;
          this.waitTime = pWT;
          this.threadId = Long.toString(System.currentTimeMillis());
     public void run(){
          FileInputStream fis = null;
          try{
               fis = new FileInputStream(this.filename);
               int readed;
               while((readed=fis.read())!=-1){
                    System.out.println("{reader["+this.threadId+"]/readed["+readed+"]}");
                    Thread.sleep((long)this.waitTime);
               System.out.println("{reader["+this.threadId+"]/EOF reached.}");
          }catch(Exception ex){
               System.out.println("{reader["+this.threadId+"]/EXCEPTION["+ex.getMessage()+"]}");
          }finally{
               this.closeFIS(fis);
               fis = null;
     private void closeFIS(FileInputStream pFis){
          if(pFis != null){
               try{
                    pFis.close();
               }catch(Exception e){
                    e.printStackTrace();
package iotests;
import iotests.IOTWriterThread;
import iotests.IOTReaderThread;
public class IOTestClass {
     private int waitTime;
     public IOTestClass(int pWT){
          this.waitTime = pWT;
     public void go(){
          // read the original file (thread1)
          IOTReaderThread iotr1 = new IOTReaderThread("c:\\file.txt",this.waitTime);
          iotr1.start();
          //wait some millis
          try{Thread.sleep(50);}catch(Exception e1){}
          // read the original file (thread2)
          IOTReaderThread iotr2 = new IOTReaderThread("c:\\file.txt",this.waitTime);
          iotr2.start();
          //wait some millis
          try{Thread.sleep(50);}catch(Exception e1){}
          // read the original file (thread3)
          IOTReaderThread iotr3 = new IOTReaderThread("c:\\file.txt",this.waitTime);
          iotr3.start();
          //wait some millis
          try{Thread.sleep(1000);}catch(Exception e1){}          
          // write in the same file (while reader is still reading the original file)
          // this will force a EOF to any reader thread
          IOTWriterThread iotw1 = new IOTWriterThread("c:\\file.txt",5,this.waitTime);
          iotw1.start();     
          //wait some millis
          try{Thread.sleep(500);}catch(Exception e1){}
          // read the same file, that now is being written
          IOTReaderThread iotr4 = new IOTReaderThread("c:\\file.txt",this.waitTime);
          iotr4.start();
      * @param args
     public static void main(String[] args) {
          IOTestClass IOTC = new IOTestClass(500);
          IOTC.go();
}

Yes...when you chain readers/writers together, you only need close the outermost reader/writer and all the inner ones close automatically.

Similar Messages

  • Close window in export to excel functionality

    Hello Everyone,
    I have created application of export to excel functionality as per following document.
    Exporting Data from Web Dynpro in Different Formats Using Open Source (POI, JExcel, iText) APIu2019s
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/d0cc41cb-9576-2b10-99a6-ab90ef28c73b
    i want to close my parent window.
    I have written the following code.
    This code for Showpopup which is called in export to excel method.
    public void showpopup( com.sap.tc.webdynpro.services.sal.url.api.WDWebResourceType resourceType, java.io.ByteArrayOutputStream OutputStream, java.lang.String title )
        //@@begin showpopup()
         IWDResource resource = null;
              resource = WDResourceFactory.createResource(OutputStream.toByteArray(),"SupplierExcel",resourceType);
              wdContext.currentContextElement().setResource(resource);
              window = wdComponentAPI.getWindowManager().createNonModalExternalWindow(resource.getUrl(WDFileDownloadBehaviour.ALLOW_SAVE.ordinal()),title);
              window.setWindowSize(50,150);
              window.setWindowPosition(WDWindowPos.CENTER);
              window.show();
              wdContext.currentContextElement().setPopwindow(window);
         wdThis.wdGetTraiexcelAppInterfaceViewController().wdFirePlugClosewindow("javascript:void(window.close())");
        //@@end
    This is method of export to excel.
    public void export_to_excel( java.util.Map columninfo, com.sap.tc.webdynpro.progmodel.api.IWDNode datanode )
        //@@begin export_to_excel()
         ByteArrayOutputStream outputStream = null;
                        HSSFWorkbook wb = null;
                        HSSFSheet sheet = null;
              try
                    outputStream = new ByteArrayOutputStream();
                    wb = new HSSFWorkbook();
                    sheet = wb.createSheet("Table1");
                    int col = 0;
                    String attributeName, trimmedHeaderText;
                    HSSFRow row = sheet.createRow(0);
                    for (Iterator iter = columninfo.keySet().iterator(); iter.hasNext();)
                        attributeName = (String) iter.next();
                    trimmedHeaderText = (String)columninfo.get(attributeName);
                    columninfo.put(attributeName, trimmedHeaderText);
                    HSSFCell cell_hed = row.createCell((short)col++);
                    cell_hed.setCellType(HSSFCell.CELL_TYPE_STRING);
                    cell_hed.setCellValue(trimmedHeaderText);
                        for(int x=0; x<datanode.size(); x++)
                                            col=0;
                                            for (Iterator iter = columninfo.keySet().iterator(); iter.hasNext();)
                                                                attributeName = (String) iter.next();
                                            HSSFRow row_data_products = sheet.createRow(x+1);
                                            IWDNodeElement ele = datanode.getElementAt(x);
                                          HSSFCellStyle cellstle = wb.createCellStyle();
                                          cellstle.setWrapText(true);
                                          cellstle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                                          cellstle.setFillBackgroundColor(HSSFColor.BLUE_GREY.index);
                                          cellstle.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
                                          HSSFFont font1 = wb.createFont();
                                          font1.setColor(HSSFColor.BLUE.index);
                                          font1.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
                                          cellstle.setFont(font1);
                                                    HSSFCell cell = row_data_products.createCell((short)col++);
                                                    cell.setCellValue(ele.getAttributeValue(attributeName).toString());
                                                    cell.setCellStyle(cellstle);
                        wb.write(outputStream);
                        showpopup(WDWebResourceType.XLS, outputStream, "XLS Out Put");
                        outputStream.close();
                        catch ( IOException ex )
                        //wdComponentAPI.getMessageManager().reportException(ex);
                        ex.printStackTrace();     
        //@@end
    Anyone can plz tell me how to close the window.
    Edited by: Abhilasha Dahare on Apr 6, 2009 3:04 PM

    Hi
    IWDWindow win = wdContext.currentContextElement().getPopwindow();
           win.destroyInstance();
    Here context element is same as u have used in opeing the popup.
    Best Regards
    Satish Kumar

  • How to close saved image?

    hi 
    I can't close the saving image after i created it. It becomes read only and  i get error  unless i exit from application when i want to create it again  i think it remains open.
    Would you help me how i can solve problem?
     ofd.Filter = "Image Files|*.jpg;*.png;*.gif;*.bmp;|All Files (*.*)|*.*"
            If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
                TextBox1.Text = ofd.FileName
                Dim img As Image = Nothing
                Dim sfilename As New System.IO.FileInfo(ofd.FileName)
                Dim yol As New FileInfo(TextBox1.Text)
                Dim f As String = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName)
                Dim path As String = yol.Directory.FullName & "\" & f & yol.Extension Dim fs As FileStream = sfilename.OpenRead()
    Dim outputStream As Stream = New MemoryStream()
    AddWatermark(fs, TextBox2.Text, outputStream)
    fs.Close()
    sfilename.Delete()
    img = Image.FromStream(outputStream)
    Using savingImage As New Bitmap(img.Width, img.Height, img.PixelFormat)
    Using g As Graphics = Graphics.FromImage(savingImage)
    g.DrawImage(img, New Point(0, 0))
    End Using
    savingImage.Save(path, ImageFormat.Jpeg)
    PictureBox1.BackgroundImage = Image.FromFile(path)
    End Using
    outputStream.Close()
    img.Dispose()Public Sub AddWatermark(ByVal fs As FileStream, ByVal watermarkText As String, ByVal outputStream As Stream)
            Dim img As Image = Image.FromStream(fs)
            Dim font As New Font("Verdana", 32, FontStyle.Bold, GraphicsUnit.Pixel)
            font = FontDialog1.Font
            'Adds a transparent watermark with an 100 alpha value.
            Dim color As Color = Color.FromArgb(100, 0, 0, 0)
            'The position where to draw the watermark on the image
            Dim pt As New Point(10, 30)
            Dim sbrush As New SolidBrush(color)
            Dim gr As Graphics = Nothing
            Try
                gr = Graphics.FromImage(img)
            Catch
                ' http://support.microsoft.com/Default.aspx?id=814675
                Dim img1 As Image = img
                img = New Bitmap(img.Width, img.Height)
                gr = Graphics.FromImage(img)
                gr.DrawImage(img1, New Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel)
                img1.Dispose()
            End Try
            gr.DrawString(watermarkText, font, sbrush, pt)
            gr.Dispose()
            img.Save(outputStream, ImageFormat.Jpeg)
        End Sub
                                                      

    Hi,
     Here is a small example that does the same thing as your code i believe and will overwrite the opened image with the watermarked image.  Perhaps you can arrange your code to follow these steps.
    Imports System.Drawing.Imaging
    Imports System.IO
    Public Class Form1
    Private Img As Bitmap
    Private wmFont As New Font("Verdana", 32, FontStyle.Bold, GraphicsUnit.Pixel)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Using ofd As New OpenFileDialog
    ofd.Filter = "Image Files|*.jpg;*.png;*.gif;*.bmp;|All Files (*.*)|*.*"
    If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
    Dim frmt As ImageFormat
    If Img IsNot Nothing Then Img.Dispose()
    Using i As New Bitmap(ofd.FileName)
    frmt = i.RawFormat
    Using g As Graphics = Graphics.FromImage(i)
    Using sb As New SolidBrush(Color.FromArgb(100, 0, 0, 0))
    g.DrawString(TextBox2.Text, wmFont, sb, New Point(10, 30))
    End Using
    End Using
    Img = New Bitmap(i)
    End Using
    Img.Save(ofd.FileName, frmt)
    If PictureBox1.Image IsNot Nothing Then PictureBox1.Image.Dispose()
    PictureBox1.Image = Img
    End If
    End Using
    End Sub
    End Class
    If you say it can`t be done then i`ll try it

  • Need help with applet servlet communication .. not able to get OutputStream

    i am facing problem with applet and servlet communication. i need to send few image files from my applet to the servlet to save those images in DB.
    i need help with sending image data to my servlet.
    below is my sample program which i am trying.
    java source code which i am using in my applet ..
    public class Test {
        public static void main(String argv[]) {
            try {
                    URL serverURL = new URL("http://localhost:8084/uploadApp/TestServlet");
                    URLConnection connection = serverURL.openConnection();
                    Intermediate value=new Intermediate();
                    value.setUserId("user123");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    connection.setDefaultUseCaches(false);
                    // Specify the content type that we will send binary data
                    connection.setRequestProperty ("Content-Type", "application/octet-stream");
                    ObjectOutputStream outputStream = new ObjectOutputStream(connection.getOutputStream());
                    outputStream.writeObject(value);
                    outputStream.flush();
                    outputStream.close();
                } catch (MalformedURLException ex) {
                    System.out.println(ex.getMessage());
                }  catch (IOException ex) {
                        System.out.println(ex.getMessage());
    }servlet code here ..
    public class TestServlet extends HttpServlet {
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
             System.out.println(" in servlet -----------");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            ObjectInputStream inputFromApplet = null;
            Intermediate aStudent = null;
            BufferedReader inTest = null;
            try {         
                // get an input stream from the applet
                inputFromApplet = new ObjectInputStream(request.getInputStream());
                // read the serialized object data from applet
                data = (Intermediate) inputFromApplet.readObject();
                System.out.println("userid in servlet -----------"+ data.getUserId());
                inputFromApplet.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("WARNING! filename.path JNDI not found");
            } finally {
                out.close();
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in foGet -----------");
            processRequest(request, response);
         * Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in doPost -----------");
            processRequest(request, response);
         * Returns a short description of the servlet.
         * @return a String containing servlet description
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>
    }the Intermediate class ..
    import java.io.Serializable;
    public class Intermediate implements Serializable{
    String userId;
        public String getUserId() {
            return userId;
        public void setUserId(String userId) {
            this.userId = userId;
    }

    Hi,
    well i am not able to get any value from connection.getOutputStream() and i doubt my applet is not able to hit the servlet. could you review my code and tell me if it has some bug somewhere. and more over i want to know how to send multiple file data from applet to servlet . i want some sample or example if possible.
    do share if you have any experience of this sort..
    Thanks.

  • JavaMapping: Convert String to OutputStream?

    Hi everybody,
    how can I convert a String to OutputStream?
    Thanks, Regards Mario

    You have to convert String to OutputStream by means of using getBytes() method..
    See the example
    public void execute(InputStream inputstream, OutputStream outputstream) throws StreamTransformationException  {
      outputstream.write("<?xml version = '1.0' encoding = 'utf-8'>".getBytes());
      outputstream.write(<ns0:outputinfo ns0=\urn:xyz\File_File\>".getBytes());
      String newline=null;
      BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
      StringBuffer sb = new StringBuffer();
      while(newline = br.readLine())!=null)
       String empno=null;
       String empname=null;
       String native=null;
       char[] chr = new char[100];
       chr = newline.toCharArray();
       String[] data = new String[10];
       int a = 0;
       int b = 2;
       for(int i=0;i<newline.length(); i++)
        if(chr<i>==',')
    data[a]=newline.substring(b,i);      
    a=a+1;      
    b=i+1;   }
        empno=data[0];
        empname=data[1];
        native=data[2];
        outputstream.write("<Data>".getBytes());
        outputstream.write("<Record>".getBytes());
        outputstream.write(("<EmpNo>"empno"</Empno>").getBytes());
        outputstream.write(("<EmpName>"empname"</Empname>").getBytes());
        outputstream.write(("<Native>"native"</Native>").getBytes());
        outputstream.write(("</Record>".getBytes());
        outputstream.write("</Data>".getBytes());
       outputstream.write("</ns0:outputinfo>".getBytes());
      br.close();
      inputstream.close();
      outputstream.close();

  • How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap?

    How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap? Currently my program reads the data from several text files in a directory and the saves that information in a text file called output.txt. I would like to cache this data in order to use it later. How can I do this using the TreeMap Class? These are the keys,values: TreeMap The data I'd like to Cache is (date from the file, time of the file, current time).
    import java.io.*;
    public class CacheData {
      public static void main(String[] args) throws IOException {
      String target_dir = "C:\\Files";
      String output = "C:\\Files\output.txt";
      File dir = new File(target_dir);
      File[] files = dir.listFiles();
      // open the Printwriter before your loop
      PrintWriter outputStream = new PrintWriter(output);
      for (File textfiles : files) {
      if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
      BufferedReader inputStream = null;
      // close the outputstream after the loop
      outputStream.close();
      try {
      inputStream = new BufferedReader(new FileReader(textfiles));
      String line;
      while ((line = inputStream.readLine()) != null) {
      System.out.println(line);
      // Write Content
      outputStream.println(line);
      } finally {
      if (inputStream != null) {
      inputStream.close();

    How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap? Currently my program reads the data from several text files in a directory and the saves that information in a text file called output.txt. I would like to cache this data in order to use it later. How can I do this using the TreeMap Class?
    I don't understand your question.
    If you don't know how to use TreeMap why do you think a TreeMap is the correct solution for what you want to do?
    If you are just asking how to use TreeMap then there are PLENTY of tutorials on the internet and the Java API provides the methods that area available.
    TreeMap (Java Platform SE 7 )
    Are you sure you want a map and not a tree instead?
    https://docs.oracle.com/javase/tutorial/uiswing/components/tree.html

  • Issue with Reading and Writing to a File

    Hello all,
    I'm having trouble when I run the following example;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.IOException;
    public class ReadWriteTextFile {
        private static void doReadWriteTextFile() {
            try {
                // input/output file names
                String inputFileName  = "README_InputFile.txt";
                String outputFileName = "ReadWriteTextFile.out";
                // Create FileReader Object
                FileReader inputFileReader   = new FileReader(inputFileName);
                FileWriter outputFileReader  = new FileWriter(outputFileName);
                // Create Buffered/PrintWriter Objects
                BufferedReader inputStream   = new BufferedReader(inputFileReader);
                PrintWriter    outputStream  = new PrintWriter(outputFileReader);
                outputStream.println("+---------- Testing output to a file ----------+");
                outputStream.println();
                String inLine = null;
                while ((inLine = inputStream.readLine()) != null) {
                    outputStream.println(inLine);
                outputStream.println();
                outputStream.println("+---------- Testing output to a file ----------+");
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                System.out.println("IOException:");
                e.printStackTrace();
        public static void main(String[] args) {
            doReadWriteTextFile();
    }Im getting the error
    java.io.FileNotFoundException: README_InputFile.txt (The system cannot find the file specified)However the file README_InputFile.txt is definately in the same folder as the class file. So why is this not working?
    Any help would be greatly appreciated.
    Jaz

    Sorry you've lost me. All I get are error messages
    when I try to compile that statement. What am I
    missing?I don't know, it should work:
    import java.io.*;
    public class Test {
    public static void main(String[] args) throws
    IOException {
    System.out.println(new
    File(".").getCanonicalPath());
    Sorry I forgot to add the "throws IOException" bit. It works and told me that the path is;
    C:\Documents and Settings\Jaz\workspace\Tutorial
    I've amended the code so it now looks like this;
    String inputFileName  = "C:/Documents and Settings/Jaz/workspace/TutorialREADME_InputFile.out";
                String outputFileName = "C:/Documents and Settings/Jaz/workspace/TutorialReadWriteTextFile.out";but I still get the error below even though the files are present in that directory;
    IOException:
    java.io.FileNotFoundException: C:\Documents and Settings\Jaz\workspace\TutorialREADME_InputFile.out (The system cannot find the file specified)

  • Creating a JButton for each line in a txt file

    I need to know how to creating a JButton for each line in a txt file then add an actionListener to the number of buttons (note they are in a JTable). Here is a clipet of code thanx for the help (note that this is one part of a program i am making there are 2 more classes. If u need them just ask) Thanx:
    class Diary extends JFrame implements ActionListener {
         private JTextArea note;
         private JTextField name;
         private JMenuBar menu = new JMenuBar();
         private JMenu file, edit, font, background, tcolor, settings, help;
         private JMenuItem nu, copy, paste, save, exit, b8, b10, b12, b14, b16, b18, b20, b24, b30, bblue, bred, bgreen, bpink, cblue, cred, cgreen, cpink, eset, nver, using, about;
         private String[] columnNames = {
              "File"
         private Vector dat = new Vector();
         private JTable filetable;
         public Diary() {
              setSize(new Dimension(500, 500));
              setTitle("Diary 2.00");
              file = new JMenu("File");
              menu.add(file);
              nu = new JMenuItem("new");
              nu.addActionListener(this);
              file.add(nu);
              file.add(new JSeparator());
              copy = new JMenuItem("copy");
              copy.addActionListener(this);
              file.add(copy);
              paste = new JMenuItem("paste");
              paste.addActionListener(this);
              file.add(paste);
              file.add(new JSeparator());
              save = new JMenuItem("Save");
              save.addActionListener(this);
              file.add(save);
              file.add(new JSeparator());
              exit = new JMenuItem("exit");
              exit.addActionListener(this);
              file.add(exit);
              edit = new JMenu("Edit");
              menu.add(edit);
              font = new JMenu("font");
              edit.add(font);
              b8 = new JMenuItem("8");
              b8.addActionListener(this);
              font.add(b8);
              b10 = new JMenuItem("10");
              b10.addActionListener(this);
              font.add(b10);
              b12 = new JMenuItem("12");
              b12.addActionListener(this);
              font.add(b12);
              b14 = new JMenuItem("14");
              b14.addActionListener(this);
              font.add(b14);
              b16 = new JMenuItem("16");
              b16.addActionListener(this);
              font.add(b16);
              b18 = new JMenuItem("18");
              b18.addActionListener(this);
              font.add(b18);
              b20 = new JMenuItem("20");
              b20.addActionListener(this);
              font.add(b20);
              b24 = new JMenuItem("24");
              b24.addActionListener(this);
              font.add(b24);
              b30 = new JMenuItem("30");
              b30.addActionListener(this);
              font.add(b30);
              background = new JMenu("background");
              edit.add(background);
              bblue = new JMenuItem("blue");
              bblue.addActionListener(this);
              background.add(bblue);
              bred = new JMenuItem("red");
              bred.addActionListener(this);
              background.add(bred);
              bgreen = new JMenuItem("green");
              bgreen.addActionListener(this);
              background.add(bgreen);
              bpink = new JMenuItem("pink");
              bpink.addActionListener(this);
              background.add(bpink);
              tcolor = new JMenu("text color");
              edit.add(tcolor);
              cblue = new JMenuItem("blue");
              cblue.addActionListener(this);
              tcolor.add(cblue);
              cred = new JMenuItem("red");
              cred.addActionListener(this);
              tcolor.add(cred);
              cgreen = new JMenuItem("green");
              cgreen.addActionListener(this);
              tcolor.add(cgreen);
              cpink = new JMenuItem("pink");
              cpink.addActionListener(this);
              tcolor.add(cpink);
              settings = new JMenu("Settings");
              menu.add(settings);
              eset = new JMenuItem("Edit Settings");
              eset.addActionListener(this);
              settings.add(eset);
              help = new JMenu("Help");
              menu.add(help);
              using = new JMenuItem("Using");
              using.addActionListener(this);
              help.add(using);
              about = new JMenuItem("About");
              about.addActionListener(this);
              help.add(about);
              help.add(new JSeparator());
              nver = new JMenuItem("new Versions");
              nver.addActionListener(this);
              help.add(nver);
              note = new JTextArea("");
              try {
                   BufferedReader filein = new BufferedReader(new FileReader("files.txt"));
                   String sfile;
                   while ((sfile = filein.readLine()) != null) {
                        //add buttons per each line of the txt file and show em
              catch (FileNotFoundException ioe) {
                   JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
              catch (IOException ioe) {
                   JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);JOptionPane.showMessageDialog(null, "Iternal Error, contact [email protected] if the error persists", "", JOptionPane.WARNING_MESSAGE);
              String[][] data = new String[dat.size()][];
              for (int x = 0; x < dat.size(); x++) {
                   data[x] = (String[])dat.get(x);
              filetable = new JTable(data, columnNames);
              filetable.setPreferredScrollableViewportSize(new Dimension(100, 500));
              JScrollPane scrollpane = new JScrollPane(filetable);
              name = new JTextField("diary");
              JPanel main = new JPanel(new GridLayout(0, 1));
              getContentPane().add(note);
              getContentPane().add(name, BorderLayout.SOUTH);
              getContentPane().add(scrollpane, BorderLayout.WEST);
              setJMenuBar(menu);
         public void actionPerformed(ActionEvent e) {
              if (e.getSource() == nu) {
                   int nuask = JOptionPane.showConfirmDialog(Diary.this, "Are you sure you want to make a new entry?\nThis will erease any unsaved entry's!!");
                   if (nuask == JOptionPane.YES_OPTION) {
                        note.setText("");
                        note.setBackground(Color.WHITE);
                        note.setForeground(Color.BLACK);
              if (e.getSource() == copy) {
                   note.copy();
              if (e.getSource() == paste) {
                   note.paste();
              if (e.getSource() == save) {
                   try {
                        String sn = name.getText();
                    FileWriter outputStream = new FileWriter("saved/" + sn + ".txt");                            
                    setTitle("Diary 1.00 : " + sn);
                    outputStream.write(note.getText());
                    outputStream.close();
                catch(IOException ioe) {
                     System.out.println("IOException");
              if (e.getSource() == exit) {
                   int exitask = JOptionPane.showConfirmDialog(Diary.this, "Are you sure you want to exit? Any unsaved entries will be deleted");
                   if (exitask == JOptionPane.YES_OPTION) {
                        System.exit(0);
              if (e.getSource() == b8) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),8));
              if (e.getSource() == b10) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),10));
              if (e.getSource() == b12) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),12));
              if (e.getSource() == b14) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),14));
              if (e.getSource() == b18) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),18));
              if (e.getSource() == b20) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),20));
              if (e.getSource() == b24) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),24));
              if (e.getSource() == b30) {
                   note.setFont(new Font(note.getFont().getName(),note.getFont().getStyle(),30));
              if (e.getSource() == bblue) {
                   note.setBackground(Color.BLUE);
              if (e.getSource() == bred) {
                   note.setBackground(Color.RED);
              if (e.getSource() == bgreen) {
                   note.setBackground(Color.GREEN);
              if (e.getSource() == bpink) {
                   note.setBackground(Color.PINK);
              if (e.getSource() == cblue) {
                   note.setForeground(Color.BLUE);
              if (e.getSource() == cred) {
                   note.setForeground(Color.RED);
              if (e.getSource() == cgreen) {
                   note.setForeground(Color.GREEN);
              if (e.getSource() == cpink) {
                   note.setForeground(Color.PINK);
              if (e.getSource() == eset) {
                   new UserSettings().setVisible(true);
              if (e.getSource() == about) {
                   JOptionPane.showMessageDialog(null, "Created by Collin Doering 2005 in Gr.9\n\nErrors:\n------------------------------------------------------------------\n1. No File Encryption\n2. No user and password Encryption", "", JOptionPane.INFORMATION_MESSAGE );
              if (e.getSource() == nver) {
                   JOptionPane.showMessageDialog(null, "New Version |3.00| expected July, 2005\n\nNew Features\n----------------------------------------------\n1. File Encryption\n2. User File Encryption\n3. Full help dialog\n4. More Text changing features", "", JOptionPane.INFORMATION_MESSAGE);
              if (e.getSource() == using) {
                   JOptionPane.showMessageDialog(null, "Go ask Collin Doering\[email protected]", "", JOptionPane.INFORMATION_MESSAGE );
    THANK YOU

    so i still do not understand how i would create one
    button per each line in a txt flle then read in the
    file that the txt file specified.This assumes you know how many lines there are in the file.
    If not, modify as per my prior post
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      String[] linesInFile = {"Hello","World","Goodbye","Now"};
      JButton[] btn = new JButton[linesInFile.length];
      public Testing()
        setLocation(200,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel jp = new JPanel(new GridLayout(0,1));
        for(int x = 0; x < btn.length; x++)
          btn[x] = new JButton(linesInFile[x]);//<---this would be where file.readLine() goes
          jp.add(btn[x]);
          btn[x].addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
              JOptionPane.showMessageDialog(getContentPane(),ae.getActionCommand());}});
        getContentPane().add(jp);
        pack();
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Adding line to txt file and then rename

    Hello there. I am trying to create a class that will add a line to a txt file and then if the nuber of lines are greater than 5 it will rename the file.
    I think I have solved it with this class.
    My problem is that the file2.renameTo does not work does anyone have any suggestions why?
             public void CopyLines(String string, String location, String fileName) throws IOException {
                 BufferedReader inputStream = null;
                 PrintWriter outputStream = null;
                   GregorianCalendar calendar = new GregorianCalendar(Locale.UK);
                boolean b=false;
                 try {
                     int counter = 0;
                      File file2 = new File(location + fileName);
                      ArrayList arrays = new ArrayList();
                      if (file2.exists()){
                     inputStream =
                         new BufferedReader(new FileReader(file2));
                     String l;
                     while ((l = inputStream.readLine()) != null) {
                          arrays.add(l);
                         counter++;
                     outputStream =
                         new PrintWriter(new FileWriter(location + fileName));
                      if (!arrays.isEmpty()){
                           for(int i= 0; i<arrays.size();i++){
                              outputStream.println(arrays.get(i));
                     outputStream.println(string);
                     if (counter>5){
                          String newFileName = location + fileName + calendar.getTime().getTime();
                          b = file2.renameTo(new File(newFileName));
                 } finally {
                     if (inputStream != null) {
                         inputStream.close();
                     if (outputStream != null) {
                         outputStream.close();
             }

    What is ". . .does not work. . ."?

  • How to write to file Unicode characters

    I have PDF files that I need to copy some strings out of and put them in various fields in a Postgres database. The goal is a Java screen into the database, whiere I mark and copy the PDF text and then paste it into a field in a Swing window, and from there into the database.
    I am unsuccessful at reading a PDF file, so I have opted to cut and paste the PDF file into an MS word file. This results in errors in certain unicode characters. I am trying to rectify them by a simple program, a start of which is below, by a replacement of the erroneous char by the proper unicode symbol. As, shown by the following, I cannot figure out how to write out a unicode character. Do I need to wrap (which I don't know much about yet)? Or do I have a file problem? (I have a Vista machine.) I don't think it should be impossible to write unicode into a file, as I am able to write into MS Word files phonological symbols, Russian, and Sanskrit. So, it must be in the java.
    P.S.: I am reading Schildt's Java: A Beginner's Guide and am through chapter10, but remaining chapters are on threads, enumerations, autoboxing, static import, annotations; generics,; applets, events, and miscellaneous topics, and, finally Swing. Maybe its in the autoboxing?
    Any help would be most appreciated.
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.IOException;
    public class CopyCharacters {
    public static void main(String[] args) throws IOException {
    FileReader inputStream = null;
    //FileWriter outputStream = null;
    PrintWriter outputStream = null;
         char longa = 0x0101;
         int longc = 0x0101;
         char capA = 0x0041;
         char longb = 0x0111;
    // Unicode for uppercase Greek omega character char uniChar = '\u039A'
         char uniChar = '\u039A';
    // Character ca = new Character('0x0101'); // illegal
         Character cb = new Character('\u0101');
         Character cc = '\u0101';
    int c;
    try {
    inputStream = new FileReader("Cardona1.txt");
    outputStream = new
                   PrintWriter(new FileWriter(
                        "characteroutput.txt"));
              outputStream.println( "character1 " + capA); //yields A
              outputStream.println( "character2 " + longa); //yields ?
              outputStream.println( "character3 " + '\u0101'); //yields ?
              outputStream.println( "character4 " + longc); //yields 257
              outputStream.println( "character5 " + "S\u00ED Se\u00F1or"); // yields character Sí Señor
              outputStream.println( "character6 " + "S'\u00ED' Se\u00F1or"); // yields S'í' Señor
              outputStream.println( "character7 " + "S\u0121 Se\u00F1or"); // yields character S? Señor
              outputStream.println( "character8 " + "S'\u0121' Se\u00F1or"); // yields character S'?' Señor
              outputStream.println( "character9 " + uniChar);// yields character ?
              outputStream.println( "character10 " + '\u00FF');// yields character ÿ but fails on \u0100.
    // only 0-255!!
              outputStream.println( "character11 " + cc);// yields ?
              outputStream.println( "character12 " + cb);// yields ?
              outputStream.println( "character13 ?");// yields ?
    while ((c = inputStream.read()) != -1) {
         // outputStream.writeln(c);- error
    } finally {
    if (inputStream != null) {
    inputStream.close();
    if (outputStream != null) {
    outputStream.close();
    }

    I am unsuccessful at reading a PDF file, so I have opted to cut and paste the PDF file into an MS word file. This results in errors in certain unicode characters.Stop right there. You are digging a hole. Stop digging. Fix the problems with reading the PDF file.

  • Performace of InputStreamReader versus Bufferedreader

    Hi,
    I have a scenario where I read a file and need to perform a encoding operation.
    Initally I used the readline method of BufferedReader to read the input file.There is an issue with readline() method it does not read a new line character.
    I then changed the code to read a character at a time using the InputStreamReader.
    Code Used:
              BufferedReader readableFile = null;
              BufferedWriter writableFile = null;
              FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
              Reader reader =null;
              Writer writer = null;
              int line=0;
              int n = 0;
              try{     
    File inputFile = new File(strInputFile); //Input File
              File outputFile = new File(strOutputFile); //OutputFile
                   inputStream = new FileInputStream( inputFile );
                   outputStream = new FileOutputStream( outputFile );
                   reader = new InputStreamReader(inputStream, strSourceEnc);
                   //Source Encoding Format
                   writer = new OutputStreamWriter(outputStream, strTargetEnc);
                   //Target Encoding Format
                   line = reader.read();
                   while (line!=-1) {
                   writer.write(line);
                   n++;
                   line = reader.read();
                   } catch ( Exception e ){
                        throw new Exception( "Could not do the Encoding Conversion Cause " +
                             ":"+e.getMessage() );
                   finally {
                        if(writer!=null){
                             writer.close();
                        if(reader!=null){
                             reader.close();
                        if (inputStream != null) {
                        inputStream.close();
                        if (outputStream != null) {
                        outputStream.close();
    The read method of the InputStreamReader works perfectly fine.Please let me know if there is any performance issue using the InputStreamReader.If so what are the disadvantages.
    Also please suggest if there is any other way of performing an encoding operation.
    Thank you!!

    There is an issue with readline() method it does not read a new line character.You kmean it doesn't return the newline character. It reads it all right.
    Why do you think you want the newline character? and what is stopping you appending it yourself if required? or calling BufferedWriter.newLine()?
    The read method of the InputStreamReader works perfectly fine.Please let me know if there is any performance issue using the InputStreamReader.There is a major* performance issue using the InputStreamReader to read character by character. This will execute orders of magnitude slower than BufferedReader. Same applies to OutputStreamWriter vs. BufferedWriter.
    If so what are the disadvantages.The disadvantage is that there is a major performance issue using the InputStreamReader. Also, you have to write all that code that is already written for you in BufferedReader. It is also already tested, and debugged, and supported, by someone else. Free.
    Also please suggest if there is any other way of performing an encoding operation.FileReader and FileWriter, but you were on the right track in the first place. Just call BufferedReader.readLine() folllowed by BufferedWriter.write() and BufferedWriter.newLine(). Rinse and repeat; close when you get a null from readLine().

  • Problems with RandomAccessFile

    Hello!
    I have a problem with reading data from file which was written with RandomAccessFile
    I write data with writeChars() method and then try to read what i wrote with readLine() method.
    But if i wrote ie 3333
    when i read it i have *3*3*3*3
    * = looks like small square ( it seems to me that it is just a free space)
    Does anybody know why this happens?
    Look please at this code with my explanations :
    public static void main(String[] args){
       try{
            RandomAccessFile outputStream = new  RandomAccessFile("a/new.data", "rw");
            outputStream.seek(0);
            outputStream.writeChars("3333" + "\n");
            outputStream.writeChars("test");
            outputStream.seek(0);
            String s = outputStream.readLine();
            String s1 = outputStream.readLine();
            System.out.println(s + " s");// here i receive instead 3333     *3*3*3*3  ( * is a small square)
            System.out.println(s1  + " s1" ); // the same thing
            outputStream.close();
        }catch(Exception exc){System.out.println("exception");}
    }Thank you for any ideas.
    Timur.

    The funky characters you are seeing are bytes with value of 0 read by readString(), converted into Java chars.
    Your problem is as follows: you write data with writeChars() which writes every character using writeChar() [which in turn writes every char as a 2-byte value, high byte first] but you read data using readLine() which uses read() in a loop. read() reads every single byte of data from the file and converts it into a 16-bit Java char.
    Thus, you double the length of your "string" by inserting zeros (for an ASCII string) when you read it back in your code.
    There are several ways to make sure you read back correct data:
    - write it using writeBytes() -- but be aware that this will discard the high byte of every char and this is only good for ASCII etc [i.e. your code will not be Unicode-friendly]
    - write the string using writeUTF() and read it via readUTF(). This will be Unicode-friendly but will not allow you to use readLine(). However, that method is documented as not being Unicode-firiendly, see
    http://java.sun.com/j2se/1.3/docs/api/java/io/RandomAccessFile.html#readLine()
    - do not use a RandomAccessFile at all. Instead, use a FileWriter to write your data and a BufferedReader wrapping a FileReader to read your data.
    Vlad.

  • Serialize an Object

    have an Automotive class which has the following methods.
    Iam able to read the i/p file and print the o/p in another file.
    But when iam trying to serialize the Automotive class a .dat file is created but the o/p is not printed.
    Can we do the serialize the Automotive object in the same class as i have done below??????????
    Or should i create an instance of the class in the main() and then serialize()???
    help required.
    Here's the code below:
    public class Automotive implements Serializable{
    BufferedReader inputstream;
    BufferedWriter outputstream;
    StringTokenizer st;
    OptionSet[] os= new OptionSet[50];//Instantiating OptionSet Class
    private int coo[]=new int[50];//count of options
    private String noo[]=new String[50];//array of options names
    private int price[]=new int[50];//array of options price
    private String type[]=new String[50];//array of option sets
    private static final long serialVersionUID = 1L;
    public void readFile()
    try
    inputstream = new BufferedReader(new FileReader("C:\\CarInputData.txt"));
    outputstream = new BufferedWriter(new FileWriter("C:\\CarOutputData.txt"));
    String line= inputstream.readLine();
    st = new StringTokenizer(line,":");
    outputstream.write("Car Model :" + st.nextToken());
    outputstream.newLine();
    inputstream.close();
    outputstream.close();
    }//end of try block
    public void serializeAuto(Automotive a)
    try
    ObjectOutputStream output=new ObjectOutputStream(new FileOutputStream("C:\\CarData.dat"));
    output.writeObject(a) ;
    output.flush();
    output.close();
    public void deserializeAuto()
    Automotive a;
    try
    ObjectInputStream input=new ObjectInputStream(new FileInputStream("C:\\CarData.dat"));
    a = (Automotive) input.readObject();
    }

    I am confused by what you write. Serialized data is binary, not text:
    import java.io.*;
    public class SerExample implements Serializable {
        private String message;
        public void setMessage(String message) {
            this.message = message;
        public String getMessage() {
            return message;
        public String toString() {
            return getMessage();
        public static void main(String[] args) throws Exception {
            SerExample obj1 = new SerExample();
            obj1.setMessage("Hello, World!");
            File file = new File("temp.ser");
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(obj1);
            out.flush();
            out.close();
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            SerExample obj2 = (SerExample) in.readObject();
            in.close();
            System.out.println(obj2);
    }Take a look at temp.ser after running this code.

  • PrintWriter strange behaviour

    PrintWriter outputStream = new PrintWriter(new FileWriter(filenameOut));
    BufferedReader inputStream = new BufferedReader(new FileReader(filenameIn));I create a PrinterWriter like so, then I read a line of text from a text file using a BufferedReader wrapped around a FileReader. Each line of text is read by BufferedReader's readLine() method. And each line is written using the PrintWriter's println() method.
    The weird behaviour occured while running my application twice, the first iteration and second iteration output different Strings to a text file, using the same println() method of PrintWriter and each String not containing a newline character. The lengths of the two files differed, one was off by 10 lines after reading in 50 thousand lines. It took me twenty minutes to plug in flush() after every invocationg of the println() method from PrintWriter to resolve the issue. Both the PrintWriter and BufferedReader were closed after processing.
    Any possible explanations for this? I assume it's not a bug but my own personal misuse.
    Mel

    Here is an SSCCE.
    To reiterate the SSCCE below is run twice, for each run the filenameOut is changed as it can only be a non existing file (a constraint is in place). And to describe the problem in this SSCCE, there is one line that is commented/uncommeted depending on the run, refer to the body of the SSCCE for more detail.
    As you can see each run writes a different String to the file, but they both write the String on the same criteria. The String written can not be null and does not contain any new line characters. Even though both streams are closed after use, I am required to flush after each String is written to the file for both files produced in each run to have the same line count total. Otherwise if I don't flush() they differ by 10 lines. On inspection of the files, it appears one file was truncated by 10 lines at the end of the file. Approximately 50 thousand lines are processed.
    And to the replys: No exceptions are produced. Also both output filenames must be unique, they must not exist yet (again constraint in place).
    private void readThenWriteToEncodedFile(String filenameIn, String filenameOut) {
      BufferedReader inputStream = null;
      PrintWriter outputStream = null;
      try {
        inputStream = new BufferedReader(new FileReader(filenameIn));
        outputStream = new PrintWriter(new FileWriter(filenameOut));
        String line = null;
        while( (line = inputStream.readLine()) != null ) {
          String[] tokens = line.split("\t");
          if (tokens.length == 3) {
             * One of the outputStream lines below is commented out, for the two runs.
            outputStream.println(tokens[0].trim() + "\t" + tokens[1].trim() + "\t" + tokens[2].trim());  //used for first run
            //outputStream.println(tokens[tokens.length - 1].trim());  //used for second run
            outputStream.flush();  //without flushing, the files produced by the two runs differ in line size by approximately 10 lines after 50 thousand lines are processed
      } catch (IOException e) {
           e.printStackTrace();
      } finally {
        try {
          if(inputStream != null) {
            inputStream.close();
          if(outputStream != null) {
            outputStream.close();
        } catch(IOException e) {
          e.printStackTrace();
    }Mel

  • Very slow GUI in web browser application

    Hello,
    I am trying to write a web browser application and I have a problem with the GUI. When the page is being loaded and set on the JEditorPane the GUI becomes very slow (actually it freezes). I don't know if this happens because of my swing implementation or because I am not using threads properly.
    I use the SwingWorker class. I created a worker thread which loads the web page and then sets it to the JEditorPane.
    Could you give me some ideas please? Below are some parts of my code.
    Thank you
    public class BrowserFrame extends javax.swing.JFrame {
        /** Creates new form BrowserFrame */
        public BrowserFrame() {
            initComponents();
            loadUrlsFromHistoryFile();
        private class RetrievePageTask extends SwingWorker<Void, URL> {
            private String address = null;
            RetrievePageTask(String address) {
                this.address = address;
                pageLoadProgressBar.setIndeterminate(true);
            protected Void doInBackground() {
                URL url = null;
                try {
                    url = new URL(address);
                    publish(url);
                catch(MalformedURLException exc) {
                    System.out.println(exc);
                catch(IOException exc) {
                    System.out.println(exc);
                return null;
            protected void process(List<URL> url) {
                try {
                    pageEditorPane.setPage(url.get(url.size() - 1));
                catch(IOException exc) {
                    System.out.println(exc);
                String url_str = url.get(url.size() - 1).toString();
                addressComboBox.setSelectedItem(url_str);
                addUrlToAddressComboBox(url_str);
        private void addressComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {                                                
            // Get the affected item
            Object item = evt.getItem();
            if(evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
                // Item was just selected
                if(item.toString().equalsIgnoreCase(""))
                    return;
                RetrievePageTask retrievePageTask = new RetrievePageTask(item.toString());
                retrievePageTask.execute();
            else if(evt.getStateChange() == java.awt.event.ItemEvent.DESELECTED) {
                // Item is no longer selected
                System.out.println("\nItem: " + item + " is no longer selected");           
        private void addressComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                               
            if ("comboBoxEdited".equals(evt.getActionCommand())) {
                // User has typed in a string; only possible with an editable combobox
                goButtonActionPerformed(evt);
            else if ("comboBoxChanged".equals(evt.getActionCommand())) {
                // User has selected an item; it may be the same item
                System.out.println("\nSpot TWO");
        private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {
             RetrievePageTask retrievePageTask = new RetrievePageTask(address);
             retrievePageTask.execute();
        private void pageEditorPaneHyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {                                              
            if(evt.getEventType() == javax.swing.event.HyperlinkEvent.EventType.ACTIVATED) {
                 RetrievePageTask retrievePageTask = new RetrievePageTask(evt.getURL().toString());
                retrievePageTask.execute();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    BrowserFrame surfRider = new BrowserFrame();
                    surfRider.setVisible(true);
    }

    Now it is all.
    package webbrowser;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class BrowserFrame extends javax.swing.JFrame {
        /** Creates new form BrowserFrame */
        public BrowserFrame() {
            initComponents();
            loadUrlsFromHistoryFile();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            addressLabel = new javax.swing.JLabel();
            goButton = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            pageEditorPane = new javax.swing.JEditorPane();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            homeButton = new javax.swing.JButton();
            refreshButton = new javax.swing.JButton();
            addressComboBox = new javax.swing.JComboBox();
            jLabel1 = new javax.swing.JLabel();
            statusLabel = new javax.swing.JLabel();
            pageLoadProgressBar = new javax.swing.JProgressBar();
            menuBar = new javax.swing.JMenuBar();
            fileMenu = new javax.swing.JMenu();
            openFileMenuItem = new javax.swing.JMenuItem();
            exitMenuItem = new javax.swing.JMenuItem();
            viewMenu = new javax.swing.JMenu();
            historyMenuItem = new javax.swing.JMenuItem();
            pageSourceMenuItem = new javax.swing.JMenuItem();
            toolsMenu = new javax.swing.JMenu();
            preferencesMenuItem = new javax.swing.JMenuItem();
            helpMenu = new javax.swing.JMenu();
            aboutMenuItem = new javax.swing.JMenuItem();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Surf Rider");
            setName("browserFrame");
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    formWindowClosing(evt);
            addressLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            addressLabel.setText("Address:");
            goButton.setText("GO");
            goButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    goButtonActionPerformed(evt);
            pageEditorPane.setEditable(false);
            pageEditorPane.setContentType("text/html");
            pageEditorPane.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
                public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
                    pageEditorPaneHyperlinkUpdate(evt);
            jScrollPane1.setViewportView(pageEditorPane);
            jButton1.setText("Back");
            jButton1.setEnabled(false);
            jButton2.setText("Forth");
            jButton2.setEnabled(false);
            jButton3.setText("Stop");
            jButton3.setEnabled(false);
            homeButton.setText("Home");
            homeButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    homeButtonActionPerformed(evt);
            refreshButton.setText("Refresh");
            refreshButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    refreshButtonActionPerformed(evt);
            addressComboBox.setEditable(true);
            addressComboBox.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    addressComboBoxItemStateChanged(evt);
            addressComboBox.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    addressComboBoxActionPerformed(evt);
            jLabel1.setText("Browser status: ");
            statusLabel.setText("Current status");
            pageLoadProgressBar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            fileMenu.setText("File");
            fileMenu.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    fileMenuActionPerformed(evt);
            openFileMenuItem.setLabel("Open File...");
            openFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    openFileMenuItemActionPerformed(evt);
            fileMenu.add(openFileMenuItem);
            exitMenuItem.setLabel("Exit");
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            viewMenu.setText("View");
            viewMenu.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    viewMenuActionPerformed(evt);
            historyMenuItem.setLabel("History");
            viewMenu.add(historyMenuItem);
            pageSourceMenuItem.setLabel("Page Source");
            viewMenu.add(pageSourceMenuItem);
            menuBar.add(viewMenu);
            toolsMenu.setText("Tools");
            preferencesMenuItem.setLabel("Preferences");
            toolsMenu.add(preferencesMenuItem);
            menuBar.add(toolsMenu);
            helpMenu.setText("Help");
            aboutMenuItem.setLabel("About");
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .add(jButton1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jButton2)
                    .add(6, 6, 6)
                    .add(refreshButton)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jButton3)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(homeButton)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(addressLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 56, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(addressComboBox, 0, 568, Short.MAX_VALUE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(goButton))
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1008, Short.MAX_VALUE)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(statusLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 339, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 470, Short.MAX_VALUE)
                    .add(pageLoadProgressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(goButton)
                        .add(jButton1)
                        .add(jButton2)
                        .add(homeButton)
                        .add(jButton3)
                        .add(refreshButton)
                        .add(addressLabel)
                        .add(addressComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(statusLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(pageLoadProgressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-1016)/2, (screenSize.height-724)/2, 1016, 724);
        }// </editor-fold>                       
        private class RetrievePageTask extends SwingWorker<Void, URL> {
            private String address = null;
            RetrievePageTask(String address) {
                this.address = address;
                pageLoadProgressBar.setIndeterminate(true);
            public String getAddress() {
                return address;
            public void setAddress(String newAddress) {
                address = newAddress;
            protected Void doInBackground() {
                URL url = null;
                try {
                    url = new URL(address);
                    publish(url);
                catch(MalformedURLException exc) {
                    System.out.println(exc);
                catch(IOException exc) {
                    System.out.println(exc);
                return null;
            protected void process(List<URL> url) {
                try {
                    System.out.println("\nBefore setting the editorPane");
                    pageEditorPane.setPage(url.get(url.size() - 1));
                catch(IOException exc) {
                    System.out.println(exc);
                String url_str = url.get(url.size() - 1).toString();
                url_str = url_str.toLowerCase(); // URL string is turned in lower case
                addressComboBox.setSelectedItem(url_str);
                addUrlToAddressComboBox(url_str);
                pageLoadProgressBar.setIndeterminate(false);
        private void openFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                                
    // TODO add your handling code here:
        private void viewMenuActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
        private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
        private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // Action performed when homeButton's Action Listener listens to an event. This
        // event is passed here as a parameter (evt). The selected item of the addressComboBox is
        // set to be the homePage. The browser goes to the home page.
        private void homeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            addressComboBox.setSelectedItem(homePage);
        // This method loads the URL history from the history.txt file into the vector and into the
        // addressComboBox.
        private void loadUrlsFromHistoryFile() {
            BufferedReader inputStream = null;
            addressComboBox.setSelectedItem(homePage);
            try {
                inputStream = new BufferedReader(new FileReader("history.txt"));
                String tmp;
                while((tmp = inputStream.readLine()) != null) {
                    // Adding url to history_mem vector
                    historyMem.add(tmp);
                    // Adding url to addressComboBox
                    addressComboBox.addItem(tmp);
            catch(IOException exc) {
                System.out.println(exc);
        private void addressComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {                                                
            // Get the affected item
            Object item = evt.getItem();
            if(evt.getStateChange() == java.awt.event.ItemEvent.SELECTED) {
                // Item was just selected
                System.out.println("\nItem: " + item + " was just selected");
                if(item.toString().equalsIgnoreCase(""))
                    return;
                RetrievePageTask retrievePageTask = new RetrievePageTask(item.toString());
                retrievePageTask.execute();
            else if(evt.getStateChange() == java.awt.event.ItemEvent.DESELECTED) {
                // Item is no longer selected
                System.out.println("\nItem: " + item + " is no longer selected");           
        // Action performed when an event occurs in the addressComboBox (eg Pressing enter
        // after typing the address).
        private void addressComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                               
            if ("comboBoxEdited".equals(evt.getActionCommand())) {
                // User has typed in a string; only possible with an editable combobox
                goButtonActionPerformed(evt);
            else if ("comboBoxChanged".equals(evt.getActionCommand())) {
                // User has selected an item; it may be the same item
        // Action performed when goButton's Action Listener listens to an event. This
        // event is passed here as a parameter (evt). When a valid URL is inserted, the
        // pageEditorPane is set to that URL.
        private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
            // 6 spaces added to the address. This is done for control reasons. Below we
            // use substring which causes exception when those spaces do not exist.
            String address = addressComboBox.getSelectedItem() + "      ";
            if(addressComboBox.getSelectedItem() == null || address.equalsIgnoreCase("      ") || address.equalsIgnoreCase("http://      ")) {
                JOptionPane.showMessageDialog(null, "No address specified.", "No address", javax.swing.JOptionPane.ERROR_MESSAGE);
            else {
                if(!address.substring(0, 7).equalsIgnoreCase("http://"))
                    address = "http://" + address;
                    RetrievePageTask retrievePageTask = new RetrievePageTask(address);
                    retrievePageTask.execute();
        // Action performed when closing the form window
        private void formWindowClosing(java.awt.event.WindowEvent evt) {                                  
            try {
                addUrlsToHistoryFile(historyMem);
            catch(IOException exc) {
                System.out.println(exc);
        /* This method is used to handle the case in which the user clicks on a hyperlink.
         In this case the pageEditorPane must present the contents of the URL that was
         clicked. This URL is retrieved from the evt object (which is a parameter to this
         method) with the method getURL().
        private void pageEditorPaneHyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {                                              
            if(evt.getEventType() == javax.swing.event.HyperlinkEvent.EventType.ACTIVATED) {
                 RetrievePageTask retrievePageTask = new RetrievePageTask(evt.getURL().toString());
                retrievePageTask.execute();
        // This method adds the visited URLs to the addressComboBox's item list. It takes as a
        // parameter the URL which is going to be added. If the URL is already in the list, then
        // it is not added again.
        private void addUrlToAddressComboBox(String url_str) {
            // number of items in the combo box's list
            int itemCount = addressComboBox.getItemCount();
            for(int i = 0; i < itemCount; i++) {
                if(url_str.equalsIgnoreCase((String)addressComboBox.getItemAt(i)))
                    return;
            addressComboBox.addItem(url_str);
            historyMem.add(url_str);
        // This method adds the visited URLs to the history file. It takes as a parameter the URL
        // which is going to be added.
        private void addUrlsToHistoryFile(Vector url_history) throws IOException {
            PrintWriter outputStream = null;
            try {
                outputStream = new PrintWriter(new FileWriter("history.txt"));
                for(int i = 0; i < url_history.size(); i++)
                    outputStream.println((String)url_history.get(i));
            finally {
                if(outputStream != null) {
                    outputStream.close();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    BrowserFrame surfRider = new BrowserFrame();
                    surfRider.setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JMenuItem aboutMenuItem;
        private javax.swing.JComboBox addressComboBox;
        private javax.swing.JLabel addressLabel;
        private javax.swing.JMenuItem exitMenuItem;
        private javax.swing.JMenu fileMenu;
        private javax.swing.JButton goButton;
        private javax.swing.JMenu helpMenu;
        private javax.swing.JMenuItem historyMenuItem;
        private javax.swing.JButton homeButton;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenuItem openFileMenuItem;
        private javax.swing.JEditorPane pageEditorPane;
        private javax.swing.JProgressBar pageLoadProgressBar;
        private javax.swing.JMenuItem pageSourceMenuItem;
        private javax.swing.JMenuItem preferencesMenuItem;
        private javax.swing.JButton refreshButton;
        private javax.swing.JLabel statusLabel;
        private javax.swing.JMenu toolsMenu;
        private javax.swing.JMenu viewMenu;
        // End of variables declaration                  
        // Variables decleration - able to modify
        private Vector<String> historyMem = new Vector<String>();
        private String homePage = "http://www.kaissa.gr";
        // End of variables decleration
        // PUBLIC METHODS
        // Get and Set methods for the private variables declared above
        public Vector getHistoryMem() {
            return historyMem;
        public void setHistoryMem(Vector<String> newHM) {
            historyMem = newHM;
        public String getHomePage() {
            return homePage;
        public void setHomePage(String newHP) {
            homePage = newHP;
    }

Maybe you are looking for

  • Memory Problem With 4gb Crucial Ballistix and Asus M4A785TD-V EVO

    motherBoard: ASUS M4A785TD-V EVO bios Version :2005 Video: amd hd5750 Processor: AMD PHENON II X2 550 3.100MHZ Memory: Crucial Modele Memory: blt4g3d1608dt1tx0 Capacity: 4GB greetings to all i have asus m4a785td-v evo mobo. i ve bought 4 gb crucial b

  • My audiobook download doesn't play.

    Bought War and Peace and listened to the first couple hours, and now pressing the play button has no effect. I quit the Music app on my iPad and tried again, but it still doesn't play. Any ideas?

  • Optical Drive Ribbon Clamp. Help!

    While upgrading my hard drive on my own, i managed to break what I think is the "locking bar" part of the ribbon clamp for my optical drive. Where can I find a new one, how can I fix it, or are there any other solutions for my problem? I have an iBoo

  • Settling of Cost for Production Order via WBS Element

    Hi Gurus, Just would like to briefly understand, how I can make use of the WBS Element in the Production Order (Assignment tab) to use as cost settling for a production order? How do i automate the WBS Element in the production Order for a set of giv

  • Trial Balance : monthwise

    Hi expers, My users wants to get F.01 monthwise.In F.01,if run period 2,i will get gl balances from Apr10 to May10.User wants only trial balance for Apr10,May10 like.Is there any standard functionality report. Please advise. Regards, Samaar