file reader returning null when file is not null content

J

jason

hello,

any assistance would be largely appreciated.

File FileChecker=new File("/Users/Jason/
Desktop/ad_log.txt");

if (!FileChecker.exists()){
FileChecker.createNewFile();
}else{

//build existing records.
//Existing_Records=
getContents(FileChecker);

} //here i check if
the file exists. if it doesn't i make a new one. otherwise i want to
read my old one, using getContents.



//getContents:

static public void getContents(File args) throws Exception{

String[] TempLine;

Scanner freader = new Scanner(args);
//BufferedWriter writer = new BufferedWriter(new
FileWriter(toFile));

//... Loop as long as there are input lines.
String line = null;
while (freader.hasNextLine()) {
line = freader.nextLine();
System.out.println(line);

}

//... Close reader and writer.
freader.close(); // Close to unlock.
// Close to unlock and flush to disk.
}


for some reason that i cannot figure out this is returning null.
the file is definitely not null and contains very long strings.
the strings contain new line by using:
System.out.println("what i write to my file");


any help would be largely appreciated!
 
L

Lew

jason said:
File FileChecker=new File("/Users/Jason/
Desktop/ad_log.txt");

Please use much milder indentation for readability. Four spaces is about the
maximum per indent level for Usenet.

The Java coding convention calls for variables (other than constants) to be
spelled in camel case (a form of mixed case) with the first letter lower case.

I understand you to say that the file already exists, and contains data. (It
doesn't really make sense in Java terms to refer to a file as being 'null';
variables can be 'null'.)
if (!FileChecker.exists()){
FileChecker.createNewFile();
}else{

//build existing records.
//Existing_Records=
getContents(FileChecker);

}
//here i [sic] check if the file exists. if it doesn't i [sic] make a new one.
otherwise i [sic] want to read my old one, using getContents.

//getContents:

static public void getContents(File args) throws Exception{

String[] TempLine;

Scanner freader = new Scanner(args);
//BufferedWriter writer = new BufferedWriter(new
FileWriter(toFile));

//... Loop as long as there are input lines.
String line = null;
while (freader.hasNextLine()) {
line = freader.nextLine();
System.out.println(line);

}

//... Close reader and writer.
freader.close(); // Close to unlock.
// Close to unlock and flush to disk.

There's nothing to "flush to disk" from an input.
}


for some reason that i [sic] cannot figure out this is returning null.
the file is definitely not null and contains very long strings.
the strings contain new line by using:
System.out.println("what i write to my file");

What exactly do you mean by "returning null"? There is no 'return' of any
value in the code that you show.

If you mean to say that you see no visible output, it is possible that
'System.out' is not flushed or there is some other problem with getting the
output visible to you. The business about "returning null" is certainly a red
herring.

This is extremely difficult to answer with the inaccurate terminology and lack
of an SSCCE (Simple, Self-Contained Compilable Example).
<http://sscce.org/>

You should show both the writes to the file and the attempt to read it.
 
M

markspace

jason said:
hello,

any assistance would be largely appreciated.

File FileChecker=new File("/Users/Jason/
Desktop/ad_log.txt");


This works for me:


package test;

import java.io.File;
import java.util.Scanner;

public class FileTest {

public static void main( String[] args )
throws Exception
{
System.out.println( new File(".").getAbsolutePath() );
for( String s : args ) {
getContents( new File(s) );
}
getContents( new File( "src/test/FileTest.java" ) );
}

private static void getContents( File f )
throws Exception
{
Scanner scanner = new Scanner( f );
while( scanner.hasNextLine() ) {
System.out.println( scanner.nextLine() );
}
}
}
 
J

jason

jason said:
any assistance would be largely appreciated.
                        File FileChecker=new File("/Users/Jason/
Desktop/ad_log.txt");

This works for me:

package test;

import java.io.File;
import java.util.Scanner;

public class FileTest {

     public static void main( String[] args )
             throws Exception
     {
         System.out.println( new File(".").getAbsolutePath() );
         for( String s : args ) {
             getContents( new File(s) );
         }
         getContents( new File( "src/test/FileTest.java" ) );
     }

     private static void getContents( File f )
             throws Exception
     {
         Scanner scanner = new Scanner( f );
         while( scanner.hasNextLine() ) {
             System.out.println( scanner.nextLine() );
         }
     }



}

markspace,
thank you for responding. i've realized a bit why my issue is so
annoying.

i am using the java desktop application developer in NetBeans.

When I use the following program:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package readtextfileexample;

/**
 *
 * @author amandaabdou
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
String A;
        A=FileReader("/Users/"+System.getProperty("user.name")+"/
Desktop/ad_log.txt");
System.out.println(A);
    }

    public static String FileReader(String args){
        File file = new File(args);
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;
        String For_Output="";
        try
        {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null)
            {
                contents.append(text)
                    .append(System.getProperty(
                        "line.separator"));
                For_Output+=text;
            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (reader != null)
                {
                    reader.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        // show file contents here

        return For_Output;
    }

}

in a java application in netbeans, it runs perfectly and does exactly
what i want.

if i attempt to migrate the method of FileReader to my basic desktop
application it no longer works.
this desktop application is using the exact same library imports and
is using identical code aside from one aspect. my FileReader method is
now called:
Code:
private String FileReader(String args)


when calling in this context i do not get anyone of my indicating
System prints to execute,
ie:
System.out.println("Made it to line 101"); //etc

is there a larger underlying issue i am missing?
this is my first desktop application, but i do not see why there
should be such a discrepancy.

you are correct, the code does work, both proposed by you and as noted
just now by me.

unfortunately when i migrate this code to my desktop application it
fails to read the file.


any assistance would be largely appreciated.
 
M

markspace

jason said:
if i attempt to migrate the method of FileReader to my basic desktop
application it no longer works.


Well, I can't tell you what the problem is with the program, if you
don't show it to me. All I can say is I agree the program you posted
works. The program you didn't post ... shrug, I don't know.

this desktop application


Ugh, you meant the NetBeans project type "Java Desktop Application?"

Don't use that, I don't think that JSR ever really went anywhere. It's
being maintained by one guy at Kenai now who seems to have no resources
or customers. Notice that their front page basically refers you to the
NetBeans Platform (different than the IDE) for an application framework.

https://appframework.dev.java.net/

Use the regular old "Java Application" instead, and just make regular
old Swing objects. It works fine, everybody does it. JSR 296 is, imo,
dead.
 
L

Lew

jason said:
i [sic] am using the java [sic] desktop application developer in NetBeans.

When I use the following program:

Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package readtextfileexample;

/**
*
* @author amandaabdou
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;


public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String A;
A=FileReader("/Users/"+System.getProperty("user.name")+"/[/QUOTE]

You should follow the naming conventions.
[QUOTE]
Desktop/ad_log.txt");
System.out.println(A);
}

public static String FileReader(String args){
File file = new File(args);
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
String For_Output="";
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;

// repeat until all lines is read
while ((text = reader.readLine()) != null)
{
contents.append(text)
.append(System.getProperty(
"line.separator"));
For_Output+=text;
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (reader != null)
{
reader.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}

// show file contents here

return For_Output;
}

}

in a java [sic] application in netbeans [sic], it runs perfectly and does exactly
what i [sic] want.

Case matters in Java. It's good practice to use correct case in writing about
Java matters.
if i [sic] attempt to migrate the method of FileReader to my basic desktop
application it no longer works.
this desktop application is using the exact same library imports and
is using identical code aside from one aspect. my FileReader method is
now called:
Code:
private String FileReader(String args)

And that didn't give you a compiler error?

There is a significant difference between static and instance methods. But
since we don't get the whole picture, we can't tell exactly why you didn't get
a compiler error when the method changed from static to instance.

Either way, the method name should be spelled with an initial lower-case
letter, as with variables.
<http://java.sun.com/docs/codeconv/index.html>

I also suspect that markspace is onto something with hi comments about the
"java [sic] desktop application developer".
 
J

jason

Well, I can't tell you what the problem is with the program, if you
don't show it to me.  All I can say is I agree the program you posted
works.  The program you didn't post ... shrug, I don't know.


Ugh, you meant the NetBeans project type "Java Desktop Application?"

Don't use that, I don't think that JSR ever really went anywhere.  It's
being maintained by one guy at Kenai now who seems to have no resources
or customers.  Notice that their front page basically refers you to the
NetBeans Platform (different than the IDE) for an application framework.

https://appframework.dev.java.net/

Use the regular old "Java Application" instead, and just make regular
old Swing objects.  It works fine, everybody does it.  JSR 296 is, imo,
dead.

markspace,

thank you very much for taking the time to respond and decipher my
errors.
i was using the "Java Desktop App" for ease of introducing myself to
Java GUI's. it helped and now i am taking your recommended path.

i am having one minor issue. i cannot seem to locate components where
i would like. i have made the components yet cannot place them where i
would like. if you could assist me with this one last issue i will be
on my way to completing my goal.

my current code is below.

a snippet that more aptly explains my issue is the following:
Code:
    	JLabel JLabel1 = new JLabel("Search: ");
     		//JLabel1.setHorizontalAlignment(SwingConstants.LEFT);
    	//JLabel1.setVerticalAlignment(SwingConstants.TOP);
    		JLabel1.setLocation(100, 100);

as you can notice, i am trying to use JLabel1.setLocation to denote
the desired location of my label. this does not seem to be working.

thank you in advance for any help!


Code:
//file: PopUpColorMenu.java
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class PopUpColorMenu extends JFrame
                            implements ActionListener {
  JPopupMenu colorMenu;
  Component selectedComponent;

  public PopUpColorMenu(  ) {
    super("v1.0");
    setSize(500, 200);
    setLocation(200, 200);
    addWindowListener(new WindowAdapter(  ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });

    MouseListener mouseListener = new MouseAdapter(  ) {
      public void mousePressed(MouseEvent e) { checkPopup(e); }
      public void mouseClicked(MouseEvent e) { checkPopup(e); }
      public void mouseReleased(MouseEvent e) { checkPopup(e); }
      private void checkPopup(MouseEvent e) {
        if (e.isPopupTrigger(  )) {
          selectedComponent = e.getComponent(  );
          colorMenu.show(e.getComponent(), e.getX(), e.getY(  ));
        }
      }
    };

    final Container content = getContentPane(  );
    JMenuBar menuBar = new JMenuBar(  ); //create menu bar

    JMenu File_Menu = new JMenu("File"); //create main menu item
    	File_Menu .setMnemonic(KeyEvent.VK_F);

    	JMenuItem Def_Save=new JMenuItem("Save As Default");
    	Def_Save.setMnemonic(KeyEvent.VK_S);

	Def_Save.addActionListener(new ActionListener(){

    		public void actionPerformed(ActionEvent arg0){
    			System.out.println("SAVED");
    		}
    	});

    JMenuItem Def_Restore=new JMenuItem("Restore Default");
		Def_Restore.setMnemonic(KeyEvent.VK_R);

	Def_Restore.addActionListener(new ActionListener(){

    		public void actionPerformed(ActionEvent arg0){
    			System.out.println("RESTORE");
    		}
    	});

	JMenuItem File_Exit=new JMenuItem("Exit");
    	File_Exit.setMnemonic(KeyEvent.VK_X);

    	File_Exit.addActionListener(new ActionListener(){

    		public void actionPerformed(ActionEvent arg0){
    			//System.out.println("EXITED");
    			System.exit(0);
    		}
    	});

    	File_Menu.add(Def_Save); //add as submenu
    	File_Menu.add(Def_Restore);
    	File_Menu.add(File_Exit);







    content.setLayout(new FlowLayout(  ));

    	//menuBar.add(File_Menu);
    		//setJMenuBar(menuBar);

    	JLabel JLabel1 = new JLabel("Search: ");
     		//JLabel1.setHorizontalAlignment(SwingConstants.LEFT);
    	//JLabel1.setVerticalAlignment(SwingConstants.TOP);
    		JLabel1.setLocation(100, 100);
    				content.add(JLabel1);
    	JButton button1 = new JButton("Go");
    		button1.addMouseListener(mouseListener);
    		button1.setHorizontalAlignment(SwingConstants.RIGHT);
    		button1.setVerticalAlignment(SwingConstants.BOTTOM);
    			content.add(button1);



    colorMenu = new JPopupMenu("Color");
    colorMenu.add(("Red"));
    colorMenu.add(("Green"));
    colorMenu.add(("Blue"));

    button1.addActionListener(new ActionListener(  ) {

 		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			System.out.println("Maybe");
		}

    });

    getContentPane(  ).addMouseListener(mouseListener);

    setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
    String color = e.getActionCommand(  );
    if (color.equals("Red"))
      selectedComponent.setBackground(Color.red);
    else if (color.equals("Green"))
      selectedComponent.setBackground(Color.green);
    else if (color.equals("Blue"))
      selectedComponent.setBackground(Color.blue);
  }

  private JMenuItem makeMenuItem(String label) {
    JMenuItem item = new JMenuItem(label);
    item.addActionListener( this );
    return item;
  }

  public static void main(String[] args) {
    new PopUpColorMenu(  );
  }
}
 
M

markspace

I'll decipher your code in a bit. I like how you're trying to post
complete examples now. That's good! But first I'll show you the easy
way to do it.
as you can notice, i am trying to use JLabel1.setLocation to denote
the desired location of my label. this does not seem to be working.

"There's an app for that."

Check out the GUI builder in NetBeans:

<http://netbeans.org/kb/trails/matisse.html>
 
J

jason

I'll decipher your code in a bit.  I like how you're trying to post
complete examples now.  That's good!  But first I'll show you the easy
way to do it.


"There's an app for that."

Check out the GUI builder in NetBeans:

<http://netbeans.org/kb/trails/matisse.html>

haha

thanks for humoring me. due to the fact that i have now committed to
building the GUI the good old fashioned way i am going to try my best
to steer clear of GUI's for GUI's etc.

my basic question is this:

how do i create a blank GUI layout, and place items as I want.

ie:

JButton MyButton=new JButton;
MyButton.size(10,10);
MyButton.setLocation(0,0);
JLabel MyLabel=new JLabel;
JLabel.size(2,10);
 
M

markspace

jason said:
haha

thanks for humoring me. due to the fact that i have now committed to


I'm not humoring you or answering lightly. I'm dead serious. The only
way to be productive and produce robust, multi-platform GUIs is to use a
builder tool. Trying to do this by hand is basically a fool's errand.
You'll just end up re-inventing the wheel. Put some effort into
learning how to make the builder tool do what you want, the long term
rewards are worth it.

building the GUI the good old fashioned way i am going to try my best
to steer clear of GUI's for GUI's etc.


Learning is OK, just don't loose sight of the overall goal: producing
code efficiently. Start with the Java tutorials. You'll need to
understand LayoutManagers to lay out by hand. There's lots of good
examples of how to layout components manually here:

<http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html>

You should also look up "Separation of Concerns" before rolling too many
of your own GUI components. Using a GUI builder will help keep you
honest there.

MyButton.setLocation(0,0);


Use "setBounds" to position a component manually. You will need to
remove the layout manager first, because a layout manager will call
setBounds itself to reposition its components. See this example here:

<http://java.sun.com/docs/books/tutorial/uiswing/layout/none.html>
 
J

jason

I'm not humoring you or answering lightly.  I'm dead serious.  The only
way to be productive and produce robust, multi-platform GUIs is to use a
builder tool.  Trying to do this by hand is basically a fool's errand.
You'll just end up re-inventing the wheel.  Put some effort into
learning how to make the builder tool do what you want, the long term
rewards are worth it.


Learning is OK, just don't loose sight of the overall goal: producing
code efficiently.  Start with the Java tutorials.  You'll need to
understand LayoutManagers to lay out by hand.  There's lots of good
examples of how to layout components manually here:

<http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html>

You should also look up "Separation of Concerns" before rolling too many
of your own GUI components.  Using a GUI builder will help keep you
honest there.


Use "setBounds" to position a component manually.  You will need to
remove the layout manager first, because a layout manager will call
setBounds itself to reposition its components. See this example here:

<http://java.sun.com/docs/books/tutorial/uiswing/layout/none.html>



Understood. you have done more than i bargained for. thank you. i am
definitely on my way now.

i cannot thank you enough.
 
L

Lew

jason said:
Code:
//file: PopUpColorMenu.java
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class PopUpColorMenu extends JFrame
implements ActionListener { ....
JMenu File_Menu = new JMenu("File"); //create main menu item
	File_Menu .setMnemonic(KeyEvent.VK_F);[/QUOTE]

<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>
[QUOTE]
JMenuItem Def_Save=new JMenuItem("Save As Default");
	Def_Save.setMnemonic(KeyEvent.VK_S); 
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>

....
JMenuItem Def_Restore=new JMenuItem("Restore Default");
		Def_Restore.setMnemonic(KeyEvent.VK_R); 
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>

....
	JMenuItem File_Exit=new JMenuItem("Exit");
	File_Exit.setMnemonic(KeyEvent.VK_X); 
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>

....
	JLabel JLabel1 = new JLabel("Search: ");
		//JLabel1.setHorizontalAlignment(SwingConstants.LEFT);
	//JLabel1.setVerticalAlignment(SwingConstants.TOP);
		JLabel1.setLocation(100, 100);
				content.add(JLabel1); 
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>
<http://java.sun.com/docs/codeconv/index.html>

....
public static void main(String[] args) {
new PopUpColorMenu(  );
}
}[/QUOTE]

Always confine GUI calls to the Event Dispatch Thread (EDT) or bizarre bugs 
will result.
 
J

jason

jasonwrote:


I'm not humoring you or answering lightly.  I'm dead serious.  The only
way to be productive and produce robust, multi-platform GUIs is to use a
builder tool.  Trying to do this by hand is basically a fool's errand.
You'll just end up re-inventing the wheel.  Put some effort into
learning how to make the builder tool do what you want, the long term
rewards are worth it.


Learning is OK, just don't loose sight of the overall goal: producing
code efficiently.  Start with the Java tutorials.  You'll need to
understand LayoutManagers to lay out by hand.  There's lots of good
examples of how to layout components manually here:

<http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html>

You should also look up "Separation of Concerns" before rolling too many
of your own GUI components.  Using a GUI builder will help keep you
honest there.


Use "setBounds" to position a component manually.  You will need to
remove the layout manager first, because a layout manager will call
setBounds itself to reposition its components. See this example here:

<http://java.sun.com/docs/books/tutorial/uiswing/layout/none.html>

hey,

one more question in here. everything is working beautifully, now i am
having one issue:
i am trying to run my app outside of netbeans as a .jar file. all
works well but it is in desperate need of a progress bar.

i am trying to implement the following but all i am getting is a
second blank popup window (no progress bar). i am so close (or think i
am) that i can smell it (or maybe i just need to shower).

this UI is popped up after i click a "go!" button or whatever. the
meat of the analysis code executes.

once this starts i would like to watch my progress bar do what it is
made to do. you know. progress!
Code:
public void actionPerformed(ActionEvent arg0) {


JFrame1.setSize(270, 250);
JFrame1.setLocation(200, 200);
JFrame1.setResizable(false);
Insets insets = JFrame1.getInsets();
        JFrame1.setLayout(null);
            JProgressBar JProgressBar1=new JProgressBar(0,100);
            JProgressBar1.setValue(50);
            JProgressBar1.setStringPainted(true);
            Dimension size=JProgressBar1.getPreferredSize();
 
JProgressBar1.setBounds(insets.left,insets.top,size.width,size.height);
            JFrame1.add(JProgressBar1);
                JFrame1.setVisible(true); //i can see this. and all
the applied choices are true. i cannot resize and it appears where it
should at the correct size. but lo and behold, not progressbar.

         for (int i=0;i<=Out.size()-1;i++){

                JProgressBar1.setValue(i);
//other operations..
           }
System.exit(0);
}
 
J

John B. Matthews

jason said:
once this starts i would like to watch my progress bar do what it is
made to do. you know. progress!
Code:
public void actionPerformed(ActionEvent arg0) {[/QUOTE]

This would appear to be blocking the Event Dispatch Thread. Instead use 
a SwingWorker:

<http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html>
<http://sites.google.com/site/drjohnbmatthews/randomdata>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top