Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: A headache!

  1. #1
    Junior Member
    Join Date
    Apr 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default A headache!

    Okay as of now I am working on my string builder in my program. If you've read my other posts I have been working away on a copy method.


    textField and textField1 are the selected files from my copy method, the source is textField and the target is textField1.

    I need it to be
    c:\\blahblah\\blahblah\\blah\\
    since
    c:\blahblah\blah\blah\
    wont work.

    I've been searching through the stringBuilder.insert commands and I am a bit confused, how would I go about doing what I am wanting to do?



            public void copyMethod() {
       //         JOptionPane.showMessageDialog(null, "Copying has commenced, watch the magic happen!");
     
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.insert(int );
     
     
                FileInputStream from = null;
                FileOutputStream to  = null;
     
    //Size of buffer (too much will crash)
                int buffSize = 4000; 
    //Start 
     
     
                try {    
     
     
                from = new FileInputStream(textField.toString());         //Stream from file 
     
     
                to   = new FileOutputStream(textField1.toString());      //Stream to copy file
                byte[] charBuffer = new byte[buffSize];
     
                int numRead;    //to keep track of where you are in the file
               //Loop through the file taking in buffSize bytes and copying them to textField1
                while((numRead = from.read(charBuffer)) != -1 )     // -1 so no out of bounds
                to.write(charBuffer, 0, numRead);      //This will copy code
    } 
     
                catch(Exception Ex){
     
                    Ex.printStackTrace();
     
            }
     
            }}


    Here is my whole program while starting the stringBuilder.

    package synch;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
     
    public class Synch extends JPanel {
     
     
        private JButton setSource = new JButton("Set Source");
        private JButton setTarget = new JButton("Set Target");
        private JButton copyButton = new JButton("Copy!");
        private JTextField textField = new JTextField(" ");
        private JTextField textField1 = new JTextField(" ");
        private JFileChooser fc = new JFileChooser();
     
        private JMenuItem Exit, oneWaySynch, twoWaySynch, Help, About, HelpMe;
     
     
        public Synch(){
            JFrame prog = new JFrame("Chris's file synchronization");
            prog.setSize(500,500);
            prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            JMenuBar jmb = new JMenuBar();
            prog.setJMenuBar(jmb);
            JMenu fileMenu = new JMenu("File");
            jmb.add(fileMenu);
            fileMenu.add(oneWaySynch = new JMenuItem(" One way Synch "));
            fileMenu.add(twoWaySynch = new JMenuItem(" Two way Synch "));
            fileMenu.add(Exit = new JMenuItem("Exit"));
     
            JMenu helpMenu = new JMenu("Help");
            jmb.add(helpMenu);
            helpMenu.add(HelpMe = new JMenuItem("Help"));
            helpMenu.add(About = new JMenuItem("About"));      
     
     
            prog.setLayout(new BorderLayout());    
     
            JPanel outterPanel = new JPanel();              
            outterPanel.setLayout(new GridLayout(2,1));
     
            //Set up the top panel of the outer panel
            JPanel topPannel = new JPanel();      
            topPannel.add(textField);
            textField.setPreferredSize(new Dimension(300,30));
            topPannel.add(setSource);
     
            //Set up the bottom panel of the outer panel
            JPanel bottomPanel = new JPanel(); 
            bottomPanel.add(textField1);
            textField1.setPreferredSize(new Dimension(300,30));
            bottomPanel.add(setTarget);
     
            //Add the top and bottom panels to the outer panel
            outterPanel.add(topPannel);
            outterPanel.add(bottomPanel);
     
            prog.add(outterPanel, BorderLayout.NORTH);
     
            JPanel Pane3 = new JPanel();
            fc.setControlButtonsAreShown(false);
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            Pane3.add(fc, FlowLayout.LEFT);              
            prog.add(Pane3, BorderLayout.CENTER);
     
     
     
            JPanel Pane4 = new JPanel();
            Pane4.add(copyButton, FlowLayout.LEFT);
            prog.add(Pane4, BorderLayout.SOUTH);
     
     
            Exit.addActionListener(new ActionListener(){
               public void actionPerformed (ActionEvent e){
                   exitMethod();
               }
            });
     
             oneWaySynch.addActionListener(new ActionListener(){
               public void actionPerformed (ActionEvent e){
                   oneWayMethod();
               }
            });     
     
            twoWaySynch.addActionListener(new ActionListener(){
               public void actionPerformed (ActionEvent e){
                   twoWayMethod();
               }
            });
     
             HelpMe.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   helpMethod();
                }
                });
     
             About.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   aboutMethod();           
                }
                });         
     
             setSource.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   setSourceMethod();           
                }
                });
     
             setTarget.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   setTargetMethod();           
                }
                });
     
     
             copyButton.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   copyMethod();           
                }
                });  
     
            prog.setVisible(true); //Display the window to the user!      
     
        } //end of method Synch()
     
            public void exitMethod() {
                if(JOptionPane.showConfirmDialog(null,"Are you sure you want it to close?", "Confirm Exit", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
                    System.exit(0);  
            }
     
     
            public void oneWayMethod() {
                //Read the next file in the source directory
     
                //See if it exists in the target directory
     
                //  if it does, check to see if it is EXACTLY the same file
     
                //  if not copy the file
                JOptionPane.showMessageDialog(null, "One way sync has been activated.");
     
     
            }
            public void twoWayMethod() {
                JOptionPane.showMessageDialog(null, "Two way sync has been activated.");
     
            }
     
            public void aboutMethod() {
                JOptionPane.showMessageDialog(null, "This is a file synchronization program, to speed things up, and over all make it easier for you.");
                   }
     
            public void helpMethod() {
                JOptionPane.showMessageDialog(null, "If you are needing assistance please contact me via email: egamespaypal@gmail.com or by phone 1-901-619-9413.");
     
     
            }
     
            public void setSourceMethod() {
                //read the directory that the file chooser is currently sitting on
                 textField.setText(fc.getSelectedFile().toString());
                JOptionPane.showMessageDialog(null, "The source has been locked in!");
     
     
            }
     
     
            public void setTargetMethod() {
                //read the directory that the file chooser is currently sitting on
                textField1.setText(fc.getSelectedFile().toString());
     
                JOptionPane.showMessageDialog(null, "The target location has been locked in!");
     
     
            }
     
            public void copyMethod() {
       //         JOptionPane.showMessageDialog(null, "Copying has commenced, watch the magic happen!");
     
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.insert(int );
     
     
                FileInputStream from = null;
                FileOutputStream to  = null;
     
    //Size of buffer (too much will crash)
                int buffSize = 4000; 
    //Start 
     
     
                try {    
     
     
                from = new FileInputStream(textField.toString());         //Stream from file 
     
     
                to   = new FileOutputStream(textField1.toString());      //Stream to copy file
                byte[] charBuffer = new byte[buffSize];
     
                int numRead;    //to keep track of where you are in the file
               //Loop through the file taking in buffSize bytes and copying them to textField1
                while((numRead = from.read(charBuffer)) != -1 )     // -1 so no out of bounds
                to.write(charBuffer, 0, numRead);      //This will copy code
    } 
     
                catch(Exception Ex){
     
                    Ex.printStackTrace();
     
            }
     
            }}


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: A headache!

    That's a lot of code to wade through- you might consider posting an SSCCE instead.

    Can't you just use String.replaceAll() or use a different path separator, like "/"? Or use the system file path separator: System Properties (The Java™ Tutorials > Essential Classes > The Platform Environment)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    Apr 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: A headache!

    Okay, let me see if I can break it down a little bit.

    The main problem is within my copyMethod. Everything else is working peachy! In my copyMethod textField/textField1 is the source/destination after the files are selected using the file chooser.

    I am wanting the source which is textField(source) to be copied to textField1(destination) which is the destination.

    Is that good? I am a novice when it comes to Java, still learning step by step! Thank you very much for your time.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: A headache!

    I'm still trying to work through that code, and honestly I'm not sure what the problem is. Are you just trying to strip something out of a String?

    What do you expect to happen, and what happens instead? In other words, what's "wrong" with the program as is? Where are you stuck?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: A headache!

    Is the problem with c:\blahblah\blah\blah\
    that the separators are \ vs / ?

    Why do you need to replace the \ with \\ ? Do you get an error?
    Try replacing the \ with / and see what happens. Let us know if that works.


    Try debugging the code by adding printlns to show variable values.
    I get NullPointerExceptions when I execute the code. null variables should be tested for before using them.
    Last edited by Norm; May 23rd, 2011 at 12:15 PM.

  6. #6
    Junior Member
    Join Date
    Apr 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: A headache!

    When I run the program the program has no errors and runs fine. As of now I believe the Copy method will error since I have,

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.insert(int );

    In my copy method. This can be removed, it was me working on it and not commenting it out, my apologies!

    When the program runs, I select the directory in the file chooser as my source, then I set target.

    I am wanting to copy one directory to another, so this is the problem I am facing. My current copy method does not let me do this since I think as of now it'll only copy the text that is sent to textField(source)/textField1(destination) not the files that are chosen.

    What I think I need to do is a string builder the way I was doing? I am confused.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: A headache!

    When I run the program the program has no errors and runs fine.
    Have you changed the code since you posted it? The posted version DOES NOT RUN!!!

    I made changes to it and am able to get it to run IF AND ONLY IF I press the buttons in the correct order. Push them in the wrong order and the program throws a NPE.
    The code should disable buttons that should not be pushed until the data is there.

    I am wanting to copy one directory to another
    You need to get a list of the files in a directory to be able to copy the contents of one directory to another. See the File class for methods to get a list of files.

    Why do you want to use StringBuilder? It has no use in your application.

  8. #8
    Junior Member
    Join Date
    Apr 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: A headache!

    Yes, here is the code with no errors.



    package synch;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
     
    public class Synch extends JPanel {
     
     
        private JButton setSource = new JButton("Set Source");
        private JButton setTarget = new JButton("Set Target");
        private JButton copyButton = new JButton("Copy!");
        private JTextField textField = new JTextField(" ");
        private JTextField textField1 = new JTextField(" ");
        private JFileChooser fc = new JFileChooser();
     
        private JMenuItem Exit, oneWaySynch, twoWaySynch, Help, About, HelpMe;
     
     
        public Synch(){
            JFrame prog = new JFrame("Chris's file synchronization");
            prog.setSize(500,500);
            prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            JMenuBar jmb = new JMenuBar();
            prog.setJMenuBar(jmb);
            JMenu fileMenu = new JMenu("File");
            jmb.add(fileMenu);
            fileMenu.add(oneWaySynch = new JMenuItem(" One way Synch "));
            fileMenu.add(twoWaySynch = new JMenuItem(" Two way Synch "));
            fileMenu.add(Exit = new JMenuItem("Exit"));
     
            JMenu helpMenu = new JMenu("Help");
            jmb.add(helpMenu);
            helpMenu.add(HelpMe = new JMenuItem("Help"));
            helpMenu.add(About = new JMenuItem("About"));      
     
     
            prog.setLayout(new BorderLayout());    
     
            JPanel outterPanel = new JPanel();              
            outterPanel.setLayout(new GridLayout(2,1));
     
            //Set up the top panel of the outer panel
            JPanel topPannel = new JPanel();      
            topPannel.add(textField);
            textField.setPreferredSize(new Dimension(300,30));
            topPannel.add(setSource);
     
            //Set up the bottom panel of the outer panel
            JPanel bottomPanel = new JPanel(); 
            bottomPanel.add(textField1);
            textField1.setPreferredSize(new Dimension(300,30));
            bottomPanel.add(setTarget);
     
            //Add the top and bottom panels to the outer panel
            outterPanel.add(topPannel);
            outterPanel.add(bottomPanel);
     
            prog.add(outterPanel, BorderLayout.NORTH);
     
            JPanel Pane3 = new JPanel();
            fc.setControlButtonsAreShown(false);
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            Pane3.add(fc, FlowLayout.LEFT);              
            prog.add(Pane3, BorderLayout.CENTER);
     
     
     
            JPanel Pane4 = new JPanel();
            Pane4.add(copyButton, FlowLayout.LEFT);
            prog.add(Pane4, BorderLayout.SOUTH);
     
     
            Exit.addActionListener(new ActionListener(){
               public void actionPerformed (ActionEvent e){
                   exitMethod();
               }
            });
     
             oneWaySynch.addActionListener(new ActionListener(){
               public void actionPerformed (ActionEvent e){
                   oneWayMethod();
               }
            });     
     
            twoWaySynch.addActionListener(new ActionListener(){
               public void actionPerformed (ActionEvent e){
                   twoWayMethod();
               }
            });
     
             HelpMe.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   helpMethod();
                }
                });
     
             About.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   aboutMethod();           
                }
                });         
     
             setSource.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   setSourceMethod();           
                }
                });
     
             setTarget.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   setTargetMethod();           
                }
                });
     
     
             copyButton.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent e){
                   copyMethod();           
                }
                });  
     
            prog.setVisible(true); //Display the window to the user!      
     
        } //end of method Synch()
     
            public void exitMethod() {
                if(JOptionPane.showConfirmDialog(null,"Are you sure you want it to close?", "Confirm Exit", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
                    System.exit(0);  
            }
     
     
            public void oneWayMethod() {
                //Read the next file in the source directory
     
                //See if it exists in the target directory
     
                //  if it does, check to see if it is EXACTLY the same file
     
                //  if not copy the file
                JOptionPane.showMessageDialog(null, "One way sync has been activated.");
     
     
            }
            public void twoWayMethod() {
                JOptionPane.showMessageDialog(null, "Two way sync has been activated.");
     
            }
     
            public void aboutMethod() {
                JOptionPane.showMessageDialog(null, "This is a file synchronization program, to speed things up, and over all make it easier for you.");
                   }
     
            public void helpMethod() {
                JOptionPane.showMessageDialog(null, "If you are needing assistance please contact me via email: egamespaypal@gmail.com or by phone 1-901-619-9413.");
     
     
            }
     
            public void setSourceMethod() {
                //read the directory that the file chooser is currently sitting on
                 textField.setText(fc.getSelectedFile().toString());
                JOptionPane.showMessageDialog(null, "The source has been locked in!");
     
     
            }
     
     
            public void setTargetMethod() {
                //read the directory that the file chooser is currently sitting on
                textField1.setText(fc.getSelectedFile().toString());
     
                JOptionPane.showMessageDialog(null, "The target location has been locked in!");
     
     
            }
     
            public void copyMethod() {
       //         JOptionPane.showMessageDialog(null, "Copying has commenced, watch the magic happen!");
     
     
                FileInputStream from = null;
                FileOutputStream to  = null;
     
    //Size of buffer (too much will crash)
                int buffSize = 4000; 
    //Start 
     
     
                try {    
     
     
                from = new FileInputStream(textField.toString());         //Stream from file 
     
     
                to   = new FileOutputStream(textField1.toString());      //Stream to copy file
                byte[] charBuffer = new byte[buffSize];
     
                int numRead;    //to keep track of where you are in the file
               //Loop through the file taking in buffSize bytes and copying them to textField1
                while((numRead = from.read(charBuffer)) != -1 )     // -1 so no out of bounds
                to.write(charBuffer, 0, numRead);      //This will copy code
    } 
     
                catch(Exception Ex){
     
                    Ex.printStackTrace();
     
            }
     
            }}

    I dont see how you're getting an error only if I am doing something wrong?

    I select the directory in the file chooser, I select "Set source" for the source of what I am wanting to copy.

    I select another directory i nthe file chooser, I select "Set target" for the destination of where I am wanting to copy the directory too.

    I click copy, but my copy method does not copy. That is where I thought the string builder is the problem? But it isn't? When I press copy, nothing happens that I know of.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: A headache!

    When I press copy, nothing happens
    Add some println statements to show execution flow following the press of the Copy button.

    Also print out the names of the files your are opening.

    Here's what I get when I execute the code:
    java.io.FileNotFoundException: javax.swing.JTextField[,45,5,300x30,layout=javax.swing.plaf.basic.BasicTe xtUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,b order=javax.swing.plaf.BorderUIResource$CompoundBo rderUIResource@18e18a3,flags=296,maximumSize=,mini mumSize=,preferredSize=java.awt.Dimension[width=300,height=30],caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResourc e[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIRes ource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAlignm ent=LEADING] (The filename, directory name, or volume label syntax is incorrect)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.jav a:106)
    at java.io.FileInputStream.<init>(FileInputStream.jav a:66)
    at SynchFiles2.copyMethod(SynchFiles2.java:200)
    at SynchFiles2$8.actionPerformed(SynchFiles2.java:126 )
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.jav a:6038)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3265)
    at java.awt.Component.processEvent(Component.java:580 3)
    at java.awt.Container.processEvent(Container.java:205 8)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4410)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2116)
    at java.awt.Component.dispatchEvent(Component.java:42 40)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:3986)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429 )
    at java.awt.Component.dispatchEvent(Component.java:42 40)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 599)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:121)
    Last edited by Norm; May 23rd, 2011 at 04:13 PM.

  10. #10
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: A headache!

    From that error message (and that error message alone), it looks like you're passing in a JTextField (whose toString() method returns that stuff) into the File you want to open, instead of the text displayed in the JTextField. Consult the API for useful functions to get the text.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!