Create a ReportOut text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jlgraham
    New Member
    • Jun 2008
    • 10

    Create a ReportOut text file

    I have just completed my final assignment in my intro java course. Everything compiles and works but I would like to have my EmployeeReports (output of the user input) go to a text file containing the output and keep the formatting instead of being displayed on the console. How do I start or is this beyond my scope?
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    This website is for sale! exampledepot.com is your first and best source for all of the information you’re looking for. From general topics to more of what you would expect to find here, exampledepot.com has it all. We hope you find what you are searching for!


    Should work. Been a while since I've done Java, and this looks like an old example. Maybe there is something new and better.

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      There's also an article here for it.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        That doesn't help the OP, he wants to capture whatever is printed to the System
        OutputStream (it's a PrintStream). Have a look at the System.setOut() method;
        it enables you to redirect the OutputStream. Note that it doesn't capture anything
        from System's InputStream because that stream performs a local echo, i.e. it
        doesn't echo anything to System's OutputStream. But that is nothing a little
        programming can't cure ;-)

        kind regards,

        Jos

        Comment

        • jlgraham
          New Member
          • Jun 2008
          • 10

          #5
          My assignment didn't require I send my input to a text file as we did not take file input and output in the intro class but really wanted to try it. I could get some info into into a text file by experimenting with the Scanner class but my assignment input was with JOptionPane. I have already emailed my assignment but here is the program I did with output to the screen. Just for my own personal interest, how would I code the output to a text file. Thanks to anyone who answers an old lady from Ontario.
          Code:
          //Java 1  Assignment 2 - Jackie Graham  July 3, 2008
          //import necessary java packages for program
          import javax.swing.*;
          import java.util.*;
          import java.text.*;
          
          /** class to declare variables, set up constructor and  methods to calculate date subtraction for employee data*/
          
          public class Employee
          {
          	//class attributes
          	private static int empID = 100;
          	//instance attributes
          	private String	lastName;
          	private String	firstName;
          	private String	midName;
          	private String	birthDate;
          	private String	hireDate;
          	private String  dateToday;
          	private int		hireAge;
          	private int 	presentAge;
          	private int		vacation;
          	private int 	myEmpID;
          	private double  vacCost;
          	private double 	payRate;
          	private double	otHours;
          	private double	regHours;
          	private double  yearCost;
          	private double  monthRegCost;
          	private double  monthOtCost;
          
          	//set up constructor
          	public Employee(String last, String first, String mid, String dob, String doh, double pay, double hours, double ot, int vac)
          	{
          		lastName   = last;
          		firstName  = first;
          		midName	   = mid;
          		birthDate  = dob;
          		hireDate   = doh;
          		payRate	   = pay;
          		regHours   = hours;
          		otHours    = ot;
          		vacation   = vac;
          		myEmpID    = empID++;
          	}
          	//set up methods to return values to the constructor
          	public String getLastName()
          	{
          		return lastName;
          	}
          
          	public String getFirstName()
          	{
          		return firstName;
          	}
          
          	public String getMidName()
          	{
          		return midName;
          	}
          
          	public String getBirthDate()
          	{
          		return birthDate;
          	}
          
          	public String getHireDate()
          	{
          		return hireDate;
          	}
          
          	public double getPayRate()
          	{
          		return payRate;
          	}
          
          	public double getRegHours()
          	{
          		return regHours;
          	}
          
          	public double getOtHours()
          	{
          		return otHours;
          	}
          
          	public int getVacation()
          	{
          		return vacation;
          	}
          
          	public static String getDate(String promptMsg, int numRetries, String defaultValue)//code generously supplied by instructor Sean Clarke
          	{
          		int		currNumRetries = 0;
          		String	userInput;
          		String	acceptedInput = "";
          		String	errMsg;
          
          		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy/MM/dd");
          
          		// do not allow 2 digit years, single digits days or months
          		myFormat.setLenient(false);
          		while(currNumRetries < numRetries)
          		{
          			errMsg = "";
          			userInput = JOptionPane.showInputDialog(null, promptMsg,"Enter date ....",
          											        JOptionPane.QUESTION_MESSAGE);
          
          			// depending on the input type, we will do various input checks
          			// check that the date is in the correct format
          			try
          			{
          				if(userInput.length() != 10)
          				{
          					acceptedInput = "";
          					currNumRetries++;
          					errMsg = "Please specify a date (YYYY/MM/DD)";
          				}
          				else
          				{
          					Date tmpDate = myFormat.parse(userInput);
          					acceptedInput = userInput;
          					currNumRetries = 2;
          				}
          			}
          			catch(Exception e)
          			{
          				acceptedInput = "";
          				currNumRetries++;
          				System.out.printf("SimpleDateFormat Exception was caught\n");
          				errMsg = "Please specify a valid date (YYYY/MM/DD)";
          			}
          
          			if(errMsg.length() > 0)
          			{
          				JOptionPane.showMessageDialog(null, errMsg,"Error in Input",
          											  JOptionPane.WARNING_MESSAGE);
          			}
          
          		}
          
          			if(acceptedInput.length() == 0)
          			{
          				acceptedInput = defaultValue;
          				JOptionPane.showMessageDialog(null,"Defaulting to : " + acceptedInput,"Error in Input",
          											  JOptionPane.WARNING_MESSAGE);
          			}
          			return(acceptedInput);
          		}
          
          		//methods to manipulate date information for calculations (code generously supplied by instructor Sean Clarke)
          		public static void outputMessage(String promptMsg)
          		{
          				JOptionPane.showMessageDialog(null, promptMsg,"Date Differences",
          											  JOptionPane.WARNING_MESSAGE);
          		}
          
          		public static String getDateToday()
          			{
          				Date 	today = new Date();
          				String	todayStr;
          
          				SimpleDateFormat	dateFormat = new SimpleDateFormat("yyyy/MM/dd");
          				todayStr = dateFormat.format(today);
          
          				return todayStr;
          	}
          
          		public static String hireAgeSubtraction(String birthDateStr, String hireDateStr)//code generously supplied by instructor Sean Clarke
          		{
          			int		birthDateVal, hireDateVal, yearDifference;
          			String	tmpStr;
          			String	outputString;
          
          			// since I have already verified that the date strings a valid dates I can do the
          			// following without any worries - and I don't have to trap any errors or exceptions
          			tmpStr = birthDateStr.substring(0,4)+birthDateStr.substring(5,7)+birthDateStr.substring(8,10);
          			birthDateVal = Integer.parseInt(tmpStr);
          
          			tmpStr = hireDateStr.substring(0,4)+hireDateStr.substring(5,7)+hireDateStr.substring(8,10);
          			hireDateVal = Integer.parseInt(tmpStr);
          
          			yearDifference = (hireDateVal-birthDateVal) / 10000;
          
          			return(" Age at Hire " + yearDifference);
          		}
          
          		public static String presentAgeSubtraction(String birthDateStr, String todayDateStr)//code generously supplied by instructor Sean Clarke
          			{
          				int		birthDateVal, todayDateVal, yearDifference;
          				String	tmpStr;
          				String	outputString;
          
          				// since I have already verified that the date strings a valid dates I can do the
          				// following without any worries - and I don't have to trap any errors or exceptions
          				tmpStr = birthDateStr.substring(0,4)+birthDateStr.substring(5,7)+birthDateStr.substring(8,10);
          				birthDateVal = Integer.parseInt(tmpStr);
          
          				tmpStr = todayDateStr.substring(0,4)+ todayDateStr.substring(5,7)+ todayDateStr.substring(8,10);
          				todayDateVal = Integer.parseInt(tmpStr);
          
          				yearDifference = (todayDateVal-birthDateVal) / 10000;
          
          				return(" Present Age " + yearDifference);
          		}
          		/*set method  @param the private variable vacCost is given a value equal to the value held in vCost */
          		public void setVCost(double vCost)
          		{
          			vacCost = vCost;
          		}
          		/*get method  @param returns the value of vacCost */
          		public double getVCost()
          		{
          			return vacCost = (regHours * payRate) * vacation;
          		}
          		/*set method  @paramthe private variable monthRegCost is given a value equal to the value held in mrCost */
          		public void setMonRegCost(double mrCost)
          		{
          			monthRegCost = mrCost;
          		}
          		/*get method  @param returns the value of monthRegCost */
          		public double getMonRegCost()
          		{
          			return monthRegCost = (regHours * payRate) * 4.33;
          		}
          		/*set method  @tparamhe private variable monthOtCost is given a value equal to the value held in otCost */
          		public void setMonOtCost(double otCost)
          		{
          			monthOtCost = otCost;
          		}
          		/*get method  @param returns the value of monthOtCost */
          		public double getMonOtCost()
          		{
          			return monthOtCost = otHours * (payRate * 1.5) * 4.33;
          		}
          		/*set method  @paramthe private variable YearCost is given a value equal to the value held in yCost */
          		public void setYrCost(double yCost)
          		{
          			yearCost = yCost;
          		}
          		/*get method  @param returns the value of yearCost */
          		public double getYrCost()
          		{
          			return yearCost = (getMonRegCost() + getMonOtCost()) * 12  - getVCost();
          		}
          }
          
          //Java 1  Assignment 2 - Jackie Graham  July 3, 2008
          //import necessary java packages
          import javax.swing.*;
          import java.util.*;
          import java.text.*;
          
          public class EmpMainline
          {
          	/** application to enter Employee data and the methods to sort and display the user input data */
          	public static void main(String args[])
          	{
          
          		String 		last, first, mid, payStr, hoursStr, otStr, vacStr;
          		String		birthDateStr, hireDateStr, todayDateStr;
          		String		simpleDateCalculationOutput;
          		double		pay, hours, otHours;
          		int			vac;
          		int			numEmp = 0;
          		int 		i;
          
          		Employee emp[] = new Employee[5]; //sets up my array
          
          
          			// walk through the # employees and get the input
          			for(i=0; i<emp.length; i++)
          			{
          
          			last = JOptionPane.showInputDialog(null,"Enter employee's last name",
          												    "Employee Information",
          													 JOptionPane.PLAIN_MESSAGE);   // get employee's last name
          			//statement to output input to uppercase
          			last = last.toUpperCase();
          
          			first = JOptionPane.showInputDialog(null,"Enter employee's first name",
          													 "Employee Information",
          											          JOptionPane.PLAIN_MESSAGE);   // get employee's first name
          			//statement to output input to uppercase
          			first = first.toUpperCase();
          
          			mid = JOptionPane.showInputDialog(null,"Enter employee's middle name or initial",
          												   "Employee Information",
          											        JOptionPane.PLAIN_MESSAGE);    //get employee's middle name or initial
          			//statement to output input to uppercase
          			mid = mid.toUpperCase();
          
          
          			birthDateStr = Employee.getDate("Enter date of birth (YYYY/MM/DD)", 2, "1930/01/01");
          
          			hireDateStr  = Employee.getDate("Enter date of hire (YYYY/MM/DD)", 2, "1930/01/01");
          
          			payStr = JOptionPane.showInputDialog(null,"Enter employee's hourly wage",
          												      "Employee Information",
          													   JOptionPane.PLAIN_MESSAGE);
          			pay = Double.parseDouble(payStr);
          
          			hoursStr = JOptionPane.showInputDialog(null,"Enter employee's regular weekly hours",
          													    "Employee Information",
          														 JOptionPane.PLAIN_MESSAGE);
          			hours = Double.parseDouble(hoursStr);
          
          			otStr = JOptionPane.showInputDialog(null,"Enter employee's weekly average overtime hours",
          													 "Employee Information",
          													  JOptionPane.PLAIN_MESSAGE);
          			otHours = Double.parseDouble(otStr);
          
          			vacStr = JOptionPane.showInputDialog(null,"Enter employee's vacation weeks",
          													  "Employee Information",
          													   JOptionPane.PLAIN_MESSAGE);
          			vac = Integer.parseInt(vacStr);
          
          			todayDateStr  = Employee.getDateToday();
          
          			//get the employee's age at hire
          			simpleDateCalculationOutput = Employee.hireAgeSubtraction(birthDateStr, hireDateStr);
          			Employee.outputMessage(simpleDateCalculationOutput);
          
          			//get the employee's present age
          			simpleDateCalculationOutput = Employee.presentAgeSubtraction(birthDateStr, todayDateStr);
          			Employee.outputMessage(simpleDateCalculationOutput);
          
          			emp[i] = new Employee(last, first, mid, birthDateStr, hireDateStr, pay, hours, otHours, vac);
          		}
          
          		//sort employees on their age
          		EmployeeSort.sortAge(emp);
          
          		// to produce the employee report from the yougest to the oldest
          		EmployeeReports.detailReport(emp);
          
          		//to sort on employee yearly cost
          		EmployeeSort.sortCost(emp);
          
           		//to produce the employee cost report from the lowest yearly wage to the highest
          		EmployeeReports.costReport(emp);
          
          	}
          }
          
          //Java 1  Assignment 2 - Jackie Graham  July 3, 2008
          import java.util.*;
          import java.text.*;
          
          public class EmployeeReports
          {
          	// class methods to show formatted output from the information given in the EmpMainline class
          	//report to display employee data
          	public static void detailReport(Employee emp[])
          	{
          		int		i;
          
          		System.out.println("\nEMPOLYEE INFORMATION REPORT");
          
          		for(i=0; i<emp.length; i++)
          		{
          			System.out.println("");
          			System.out.printf("Employee #: %d   %s %s (%s)\n", 100 + i, emp[i].getLastName(), emp[i].getFirstName(), emp[i].getMidName());
          			System.out.println("");
          			System.out.printf("Date of Birth:     %s\n", emp[i].getBirthDate());
          			System.out.printf("Date of Hire:      %s\n", emp[i].getHireDate());
          			System.out.printf("Hourly Pay Rate:      $%6.2f\n", emp[i].getPayRate());
          			System.out.printf("Hours Per Week: %13.1f\n", emp[i].getRegHours());
          			System.out.printf("Overtime Hours Per Week: %4.1f\n", emp[i].getOtHours());
          		}
          	}
          
          	//report to display employee costs
          	public static void costReport(Employee emp[])
          	{
          		int		i;
          
          		System.out.println("\nEMPOLYEE COST REPORT");
          
          		for(i=0; i<emp.length; i++)
          		{
          			System.out.println("");
          			System.out.printf("Employee #: %d   %s %s (%s)\n", 100 + i, emp[i].getLastName(), emp[i].getFirstName(), emp[i].getMidName());
          			System.out.println("");
          			System.out.printf("Employee Yearly Cost:    $ %9.2f\n", emp[i].getYrCost());
          			System.out.printf("Employee Monthly Cost:   $ %9.2f\n", emp[i].getMonRegCost());
          			System.out.printf("Employee Overtime Cost:  $ %9.2f\n", emp[i].getMonOtCost());
          			System.out.printf("Employee Vacation Cost:  $ %9.2f\n", emp[i].getVCost());
          
          		}
          	}
          
          }
          
          //Java 1  Assignment 2 - Jackie Graham  July 3, 2008
          
          public class EmployeeSort
          {
          	// class method (use of static) to sort on the employees age from youngest to oldest
          	public static void sortAge(Employee emp[])
          	{
          		int			i, j;
          		Employee	tmpEmp;
          
          		for(i=0; i<emp.length-1; i++)
          		{
          			for(j=0; j<emp.length-1; j++)
          			{
          				Employee	tmp1, tmp2;
          				String		tmp1BirthDate, tmp2BirthDate;
          
          				tmp1 = emp[j];
          				tmp2 = emp[j+1];
          
          				tmp1BirthDate = tmp1.getBirthDate();
          				tmp2BirthDate = tmp2.getBirthDate();
          
          
          				// comparison
          				if(emp[j].getBirthDate().compareTo(emp[j+1].getBirthDate())<0)
          				//if(tmp1BirthDate.compareTo(tmp2BirthDate) < 0)
          				{
          					tmpEmp   = emp[j];	// temporarily holds one employee
          					emp[j]   = emp[j+1];
          					emp[j+1] = tmpEmp;
          				}
          			}
          		}
          	}
          
          	//class method (static) to sort on employee cost from the lowest yearly cost to the highest
          	public static void sortCost(Employee emp[])
          		{
          			int			i, j;
          			Employee	tmpEmp;
          
          			for(i=0; i<emp.length-1; i++)
          			{
          				for(j=0; j<emp.length-1; j++)
          				{
          					Employee	tmp1, tmp2;
          					double 		tmp1YrCost, tmp2YrCost;
          
          					tmp1 = emp[j];
          					tmp2 = emp[j+1];
          
          					tmp1YrCost = tmp1.getYrCost();
          					tmp2YrCost = tmp2.getYrCost();
          
          
          					// comparison
          					//if(emp[j].getYrCost()<(emp[j+1].getYrCost())
          					if(tmp1YrCost > tmp2YrCost)
          					{
          						tmpEmp   = emp[j];	// temporarily holds one employee
          						emp[j]   = emp[j+1];
          						emp[j+1] = tmpEmp;
          					}
          				}
          			}
          	}
          
          }

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by jlgraham
            My assignment didn't require I send my input to a text file as we did not take file input and output in the intro class but really wanted to try it. I could get some info into into a text file by experimenting with the Scanner class but my assignment input was with JOptionPane. I have already emailed my assignment but here is the program I did with output to the screen. Just for my own personal interest, how would I code the output to a text file. Thanks to anyone who answers an old lady from Ontario.
            So basically you don't want to change your programs (too much) but you want
            everything that was printed through the System.out stream to end up in a file.
            Here's a way to do it: the following class takes a file name as a parameter and
            fiddles with the System.out stream. Here's how it does it:

            [code=java]
            public class Spooler {

            private static class TeeOutputStream extends OutputStream {
            ...
            }

            public static PrintStream getInstance(Str ing file) {

            try {
            OutputStream fos= new FileOutputStrea m(file);
            OutputStream tos= new TeeOutputStream (System.out, fos);

            System.setOut(n ew PrintStream(tos ));
            }

            catch (IOException ioe) { ioe.printStackT race(System.err ); }

            return System.out;
            }
            }
            [/code]

            What it does is create a FileOutputStrea m given the file name and changes the
            System.out stream to a TeeOutputStream wrapped in a PrintStream. The
            TeeOutputStream acts as an OutputStream but writes the output to the two
            OutputStreams passed in to its constructor (see below). So when you print to
            System.out, the data ends up in a PrintStream that uses a TeeOutputStream
            that in turn splits the data to two OuputStreams: the original System.out stream
            and a FileOutputStrea m.

            For convenience the getInstance() method returns the System.out stream; if
            anything failed the original stream is returned (and the error message is printed
            on the System.err stream) otherwise, if everything went fine, the altered stream
            is returned.

            Here's the definition of the TeeOutputStream :

            [code=java]
            private static class TeeOutputStream extends OutputStream {

            private OutputStream out1;
            private OutputStream out2;

            private TeeOutputStream (OutputStream out1, OutputStream out2) {

            this.out1= out1;
            this.out2= out2;
            }

            public void write (int b) throws IOException {

            out1.write(b);
            out2.write(b);
            }

            public void flush() throws IOException {

            out1.flush();
            out2.flush();
            }

            public void close() throws IOException {

            out1.close();
            out2.close();
            }
            }
            [/code]

            I've made it a private static nested class of the Spooler class because basically
            it is none of anyones business how and what this thing is. As you can see it
            flushes, closes and writes to both of its OutputStreams out1 and out2.

            You have to change your programs a bit: add the following line to the start of
            your main() methods:

            [code=java]
            Spooler.getInst ance("filename" );
            [/code]

            Now the output still shows on your screen but the output also ends up in a file
            named "filename". Of course you can use any other file name.

            Maybe you can see that you can spool your output to several files: simply repeat
            that line (see above) more than once:

            [code=java]
            Spooler.getInst ance("filename1 ");
            Spooler.getInst ance("filename2 ");
            [/code]

            kind regards,

            Jos

            Comment

            • jlgraham
              New Member
              • Jun 2008
              • 10

              #7
              Thanks for the reply Jos. It is all greek to me but kind of follow it with your explanation. Where do I put the Spooler class code. I added the line you told me to in my main and created(copied) the Spooler class in the folder with the rest of the files but get mega errors. Please understand that I didn't even know that I could print to a file until I read through the book a bit. Java 1 covers the first 6 chapters and file input output is chapter 16 but I actually typed the quick brown fox using Scanner to a file but that was all I could do. Could you please take me by the virtual hand (think of me as your mother) and walk me through the process. You can email me directly if you want. By the way I got 90% on this assignment and I have corrected the few errors(javadoc is/** */ not /* */ and why I did the empID with the for loop I don't know but fixed that as well.
              jlgraham
              Last edited by jlgraham; Jul 5 '08, 05:06 PM. Reason: Reply to the wrong place

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Normally I organize my Java sources and class files etc. as follows:

                Let X be a directory where I want to store everything, then I build the next two
                subdirectories:

                X\src
                X\classes

                I'm assuming an MS Windows machine here, otherwise use a slash instead of
                a backslash.

                All my .java source files are stored in the first directory and I make the Java
                compiler store all the .class file in the X\classes directory (see below).

                If a class has a package specified, I store the file in the corresponding subdirectory,
                e.g. for this file:

                [code=java]
                package utils; // package of this class

                public class Spooler {
                ...
                }
                [/code]

                it ends up here: X\src\utils\Spo oler.java

                Any source file without a package is simply stored in directory X\src.
                When I want to compile source files, I move to the X\src directory and use this
                command line:

                Code:
                javac -sourcepath . -d ..\classes -cp ..\classes mySourceFile.java
                The first flag "-sourcepath ." tells the compiler where it should look for .java
                source files; the second flag "-d ..\classes" tells the compiler where it should
                store the compiled .class files and the last flag "-cp ..\classes" tells it where
                it should look for already compiled files.

                Those three flags cause the compiler to do this: if a file to be compiled refers
                to another class (by using an import statement) it tries to find the compiled
                class in the directory specified by the -cp flag. If it finds it and no source happens
                to be more up to date than this .class file the compiler uses it. The possible
                source of the .class file is searched for in the directory specified by the first flag.

                If the source does happen to be more up to date (or no .class file was found),
                the source file is compiled first and the entire searching repeats itself recursively.
                So you can basically compile all your .java files when you make the compiler
                compile your main .java class source. Those three flags take care of it all.

                This way the .class files end up in a directory structure identical to the src
                directory structure, e.g. when the file utils\Spooler.j ava stored in X\src\utils
                is compiled, the result ends up in X\classes\utils \Spooler.class, exactly where
                I want it to end up.

                So you can store all your Java source files in X\src, store that Spooler.java file
                in X\src\utils and add one first line to it: "package utils;" so the compiler knows
                the file really belongs there. Move to the directory X\src and use this command line:

                Code:
                javac -sourcepath . -d ..\classes -cp ..\classes *.java
                This will compile all your .java source files, looks for other .java or .class files
                your sources may depend on and compiles them also if needed. If a class needs
                the Spooler class the compiler will search for its source or compiled form.

                All your classes that want to use this Spooler class should import it by adding
                the following line at the top of their source file "import utils.Spooler;" .

                If you want to run, say, Exercise1.class you run it like this (you're still in that X\src
                directory):

                Code:
                java -cp ..\classes Exercise1
                The "-cp ..\classes" flag tells the JVM that ..\classes is the directory to search
                for classes; where it will find them because the compiler put them there.

                Try to experiment a bit: remove everything in the ..\classes directory and compile
                everything (see above) and watch what the compiler generates; remove one or
                more of those compiler flags and see what happens and fails; it brings a bit more
                understanding of how those things actually work without any magic.

                kind regards,

                Jos

                Comment

                • jlgraham
                  New Member
                  • Jun 2008
                  • 10

                  #9
                  Originally posted by JosAH
                  Normally I organize my Java sources and class files etc. as follows:

                  Let X be a directory where I want to store everything, then I build the next two
                  subdirectories:

                  X\src
                  X\classes

                  I'm assuming an MS Windows machine here, otherwise use a slash instead of
                  a backslash.

                  All my .java source files are stored in the first directory and I make the Java
                  compiler store all the .class file in the X\classes directory (see below).

                  If a class has a package specified, I store the file in the corresponding subdirectory,
                  e.g. for this file:

                  [code=java]
                  package utils; // package of this class

                  public class Spooler {
                  ...
                  }
                  [/code]

                  it ends up here: X\src\utils\Spo oler.java

                  Any source file without a package is simply stored in directory X\src.
                  When I want to compile source files, I move to the X\src directory and use this
                  command line:

                  Code:
                  javac -sourcepath . -d ..\classes -cp ..\classes mySourceFile.java
                  The first flag "-sourcepath ." tells the compiler where it should look for .java
                  source files; the second flag "-d ..\classes" tells the compiler where it should
                  store the compiled .class files and the last flag "-cp ..\classes" tells it where
                  it should look for already compiled files.

                  Those three flags cause the compiler to do this: if a file to be compiled refers
                  to another class (by using an import statement) it tries to find the compiled
                  class in the directory specified by the -cp flag. If it finds it and no source happens
                  to be more up to date than this .class file the compiler uses it. The possible
                  source of the .class file is searched for in the directory specified by the first flag.

                  If the source does happen to be more up to date (or no .class file was found),
                  the source file is compiled first and the entire searching repeats itself recursively.
                  So you can basically compile all your .java files when you make the compiler
                  compile your main .java class source. Those three flags take care of it all.

                  This way the .class files end up in a directory structure identical to the src
                  directory structure, e.g. when the file utils\Spooler.j ava stored in X\src\utils
                  is compiled, the result ends up in X\classes\utils \Spooler.class, exactly where
                  I want it to end up.

                  So you can store all your Java source files in X\src, store that Spooler.java file
                  in X\src\utils and add one first line to it: "package utils;" so the compiler knows
                  the file really belongs there. Move to the directory X\src and use this command line:

                  Code:
                  javac -sourcepath . -d ..\classes -cp ..\classes *.java
                  This will compile all your .java source files, looks for other .java or .class files
                  your sources may depend on and compiles them also if needed. If a class needs
                  the Spooler class the compiler will search for its source or compiled form.

                  All your classes that want to use this Spooler class should import it by adding
                  the following line at the top of their source file "import utils.Spooler;" .

                  If you want to run, say, Exercise1.class you run it like this (you're still in that X\src
                  directory):

                  Code:
                  java -cp ..\classes Exercise1
                  The "-cp ..\classes" flag tells the JVM that ..\classes is the directory to search
                  for classes; where it will find them because the compiler put them there.

                  kind regards,

                  Jos
                  Thank you I was even able to follow your explanation. Are you an instructor? I will play with this with all my files. I just made a new folder for each of my assignments and exercises. This seems so much more efficient. In the fall, I might even attempt Java 2 now that I discovered there are forums for help. Once again thanks
                  An old lady from Woodstock Ontario Canada

                  Comment

                  • JosAH
                    Recognized Expert MVP
                    • Mar 2007
                    • 11453

                    #10
                    Originally posted by jlgraham
                    Thank you I was even able to follow your explanation. Are you an instructor? I will play with this with all my files. I just made a new folder for each of my assignments and exercises. This seems so much more efficient. In the fall, I might even attempt Java 2 now that I discovered there are forums for help. Once again thanks
                    An old lady from Woodstock Ontario Canada
                    You're welcome of course and no I'm not an instructor, I used to (guest) lecture
                    a bit years ago but it's not my cup of tea; I'm a mathematician who just has to
                    work with those computers a lot. btw, I was coincidentally adding one little
                    paragraph to my reply when you replied; read it and do play with the several
                    options a bit and see what happens and see how those tools actually work.

                    Also btw, a person is just as old as s/he feels; if you're attempting to learn
                    something new (and interesting!) you're not as old as you think you are.
                    Personally I'm mentally six years old and no noticable progression according
                    to my wife ;-)

                    Have fun with this Java stuff and feel free to ask relevant questions here. Note
                    the 'Howtos' section (see the blue bar near the top of this page). The Java
                    section contains a small "articles index" article that mentions a few important
                    links. Do download the API documentation; it is extremely handy and also
                    download Sun's tutorials. They're a great way to learn and experiment.

                    kind regards,

                    Jos

                    Comment

                    Working...