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.

Page 2 of 2 FirstFirst 12
Results 26 to 48 of 48

Thread: Java read in + print to a file

  1. #26
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    The PrintStream should be created one time outside of and before the loop.
    The code should not create a new PrintStream evey time the loop goes around.

    The PrintStream should be closed after all the writing to it is finished.

    It would be helpful for you if the code also printed out each line after it was read so you could see what was being read from the file.
    If you don't understand my answer, don't ignore it, ask a question.

  2. #27
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    So i can create the printstream outside of the loop but the output also cant be in the loop, so would it go before or after the loop? Since this continually outputs vet: then whatever is read.
    	try
    		{
     
    		Scanner inputScanner = new Scanner(new File(fileName));
     
    		PrintStream ps = new PrintStream(outFile);
     
    		while (inputScanner.hasNextLine()) 
     
    			{
    			String i = inputScanner.nextLine();
     
    			ps.printf("Vet: %s", i);
    			}
     
    			inputScanner.close();
     
    			} catch (Exception e) 
    				{
    				System.out.println("Exception");
    				e.printStackTrace();
    				}
     
     
     
    	}
     
    }

  3. #28
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    whatever is read.
    Did you try adding a print statement inside the loop that prints out the value that is read into i so that you know what is being read?
    Note: i is a poor variable name for a variable that hold a line of text from a file. line would be a better name.

    Also the code needs to close the PrintStream class after it is done writing to the file. That would be outside of the loop next to where the Scanner class object is closed.

    the output also cant be in the loop
    Sorry I don't understand what that means. The printf statement needs to be where it is inside the loop after the data was read.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #29
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    Yea i just put in a print statement and it is correctly reading the file, so my issue is with how i can output it nicely.

    --- Update ---

    This is what i got now, but this prints these 3 lines over and over. Also, you can see that the date line of code i need to use 3 different values that get read in and that line will not work, how would i format a line like that?
    try
    		{
     
    		Scanner inputScanner = new Scanner(new File(fileName));
     
    		PrintStream ps = new PrintStream(outFile);
     
    		while (inputScanner.hasNextLine()) 
     
    			{
    			String line = inputScanner.nextLine();
    			System.out.println(line);
    			ps.printf("Pet Vet Visit Report\r\n");
    			ps.printf("Vet: %s\r\n", line);
    			ps.printf("Date: %s/%s/%s", line, line, line);
    			}
     
     
     
    			inputScanner.close();
     
    			} catch (Exception e) 
    				{
    				System.out.println("Exception");
    				e.printStackTrace();
    				}
     
     
     
    	}

  5. #30
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    how i can output it nicely.
    Please copy and paste here a sample of the current output
    and also show an example of what you want the output to look like.


    how would i format a line like that?
    Please show the current output and the desired output.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #31
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    This is currently what the output looks like.
    Pet Vet Visit Report
    Vet: Andrea Rodriguez
    Date: Andrea Rodriguez/Andrea Rodriguez/Andrea RodriguezPet Vet Visit Report
    Vet: 9
    Date: 9/9/9Pet Vet Visit Report
    Vet: 3
    Date: 3/3/3Pet Vet Visit Report
    Vet: 2018
    Date: 2018/2018/2018Pet Vet Visit Report
    Vet: Snickers
    Date: Snickers/Snickers/SnickersPet Vet Visit Report
    Vet: Dog
    Date: Dog/Dog/DogPet Vet Visit Report
    Vet: Male
    Date: Male/Male/MalePet Vet Visit Report
    Vet: 7
    Date: 7/7/7Pet Vet Visit Report
    Vet: Rabies Shot
    Date: Rabies Shot/Rabies Shot/Rabies ShotPet Vet Visit Report
    Vet: 20.00
    Date: 20.00/20.00/20.00Pet Vet Visit Report
    Vet: 1
    Date: 1/1/1Pet Vet Visit Report
    Vet: true
    Date: true/true/truePet Vet Visit Report
    Vet: 0.75
    Date: 0.75/0.75/0.75Pet Vet Visit Report
    Vet: Distemper/Parvo Combo
    Date: Distemper/Parvo Combo/Distemper/Parvo Combo/Distemper/Parvo ComboPet Vet Visit Report
    Vet: 45.00
    Date: 45.00/45.00/45.00Pet Vet Visit Report
    Vet: 1
    Date: 1/1/1Pet Vet Visit Report
    Vet: false
    Date: false/false/falsePet Vet Visit Report
    Vet: 0.0
    Date: 0.0/0.0/0.0Pet Vet Visit Report
    Vet: Physical Therapy
    Date: Physical Therapy/Physical Therapy/Physical TherapyPet Vet Visit Report
    Vet: 100.00
    Date: 100.00/100.00/100.00Pet Vet Visit Report
    Vet: 2
    Date: 2/2/2Pet Vet Visit Report
    Vet: true
    Date: true/true/truePet Vet Visit Report
    Vet: .5
    Date: .5/.5/.5Pet Vet Visit Report
    Vet: Microchip
    Date: Microchip/Microchip/MicrochipPet Vet Visit Report
    Vet: 19.00
    Date: 19.00/19.00/19.00Pet Vet Visit Report
    Vet: 1
    Date: 1/1/1Pet Vet Visit Report
    Vet: false
    Date: false/false/falsePet Vet Visit Report
    Vet: 0.0
    Date: 0.0/0.0/0.0Pet Vet Visit Report
    Vet: Neutering
    Date: Neutering/Neutering/NeuteringPet Vet Visit Report
    Vet: 200.00
    Date: 200.00/200.00/200.00Pet Vet Visit Report
    Vet: 1
    Date: 1/1/1Pet Vet Visit Report
    Vet: true
    Date: true/true/truePet Vet Visit Report
    Vet: .8
    Date: .8/.8/.8Pet Vet Visit Report
    Vet: X ray
    Date: X ray/X ray/X rayPet Vet Visit Report
    Vet: 200.00
    Date: 200.00/200.00/200.00Pet Vet Visit Report
    Vet: 3
    Date: 3/3/3Pet Vet Visit Report
    Vet: true
    Date: true/true/truePet Vet Visit Report
    Vet: .9
    Date: .9/.9/.9Pet Vet Visit Report
    Vet: Overnight Stay
    Date: Overnight Stay/Overnight Stay/Overnight StayPet Vet Visit Report
    Vet: 200.00
    Date: 200.00/200.00/200.00Pet Vet Visit Report
    Vet: 2
    Date: 2/2/2Pet Vet Visit Report
    Vet: true
    Date: true/true/truePet Vet Visit Report
    Vet: .8
    Date: .8/.8/.8Pet Vet Visit Report
    Vet: 
    Date: //


    And this is what i need to make it look like:
    codehelp.jpg

  7. #32
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    Can you post a small section of text showing what you want, not an image?

    Use extra spacing in the format String used in printf to put the output data in columns.

    Don't post all of the incorrect output, only a few lines to show what the problem is.
    Then edit that incorrect output into the format you want.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #33
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    OK back after a couple days, i have simplified my code, this currently works to an extent. My professor today gave us pseudocode on how we should write this program. It went:
    Open input file
    Open output file
    Write header to output file
    Read header from input file
    Write report header
    While (not end of file)
    {
    read in a record
    "process" record
    Write out a report body line
    }
    write the report footer.
    I will be working on it now with this additional information. Does this change anything from your point of view?
    public static void main(String[] args) throws FileNotFoundException {
     
    		String fileName;
    		String outFile;
     
     
    		Scanner keyboardScanner = new Scanner(System.in);
     
    		System.out.printf("Enter the file name: ");
     
    		fileName = keyboardScanner.next();
     
    		System.out.printf("Enter the output file name: ");
     
    		outFile = keyboardScanner.next();
     
     
    		Scanner inputScanner = new Scanner(new File(fileName));
     
    		PrintStream ps = new PrintStream(outFile);
     
    		while (inputScanner.hasNextLine()) 
     
    			{
     
    			String line = inputScanner.nextLine();
     
    			System.out.println(line);
     
    			ps.println("Vet Report");
    			ps.println("Vet name: %s");
    			ps.println(line);
     
    			}
     
     
    			inputScanner.close();
     
    			ps.close();
     
     
     
    	}
     
    }


    --- Update ---

    OK back after a couple days, i have simplified my code, this currently works to an extent. My professor today gave us pseudocode on how we should write this program. It went:
    Open input file
    Open output file
    Write header to output file
    Read header from input file
    Write report header
    While (not end of file)
    {
    read in a record
    "process" record
    Write out a report body line
    }
    write the report footer.
    I will be working on it now with this additional information. Does this change anything from your point of view?
    public static void main(String[] args) throws FileNotFoundException {
     
    		String fileName;
    		String outFile;
     
     
    		Scanner keyboardScanner = new Scanner(System.in);
     
    		System.out.printf("Enter the file name: ");
     
    		fileName = keyboardScanner.next();
     
    		System.out.printf("Enter the output file name: ");
     
    		outFile = keyboardScanner.next();
     
     
    		Scanner inputScanner = new Scanner(new File(fileName));
     
    		PrintStream ps = new PrintStream(outFile);
     
    		while (inputScanner.hasNextLine()) 
     
    			{
     
    			String line = inputScanner.nextLine();
     
    			System.out.println(line);
     
    			ps.println("Vet Report");
    			ps.println("Vet name: %s");
    			ps.println(line);
     
    			}
     
     
    			inputScanner.close();
     
    			ps.close();
     
     
     
    	}
     
    }

  9. #34
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    No change here. I agree with your professor's pseudo code. There was one thing I would add: closing both files when done using them. I see that your code does that.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #35
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    So my code is coming along well. Its not the prettiest but it works. Except for formatting the output. Each column is not the same distance away so how can i make it so each output fits under the correct column?
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.PrintStream;
    import java.util.Scanner;
     
    public class Standalonereport {
     
    	public static void main(String[] args) throws FileNotFoundException {
     
    		String fileName;
    		String outFile;
     
     
    		Scanner keyboardScanner = new Scanner(System.in);
     
    		System.out.printf("Enter the file name: ");
     
    		fileName = keyboardScanner.next();
     
    		System.out.printf("Enter the output file name: ");
     
    		outFile = keyboardScanner.next();
     
    		PrintStream ps = new PrintStream(outFile);
     
    		Scanner inputScanner = new Scanner(new File(fileName));
    		String lineE = inputScanner.nextLine();
    		ps.println("Pet Veterinarian Visit Report");
    		ps.println("--------------------------------");
    		ps.printf("Veterinarian: %s\r\n", lineE);
    		lineE = inputScanner.nextLine();
    		ps.printf("Date: %s/", lineE);
    		lineE = inputScanner.nextLine();
    		ps.printf("%s/", lineE);
    		lineE = inputScanner.nextLine();
    		ps.printf("%s \r\n", lineE);
    		lineE = inputScanner.nextLine();
    		ps.printf("Pet Name     :  %s\r\n", lineE);
    		lineE = inputScanner.nextLine();
    		ps.printf("Pet Species  :  %s\r\n", lineE);
    		lineE = inputScanner.nextLine();
    		ps.printf("Pet Gender   :  %s\r\n", lineE);
    		lineE = inputScanner.nextLine();
    		ps.printf("Procedures   :  %s\r\n", lineE);
    		ps.printf("Name				Price	QTY	Amount		Is Covered	Pct Covered	Amount Covered		Amount Due\r\n");
     
    		while (inputScanner.hasNextLine()) 
     
    			{
     
    			String line = inputScanner.nextLine();
    			ps.printf("%20s",line);
    			System.out.println(line);
     
     
     
    			}
     
     
    			inputScanner.close();
     
    			ps.close();
     
     
     
    	}
     
    }

    Current output:
    Pet Veterinarian Visit Report
    --------------------------------
    Veterinarian: Andrea Rodriguez
    Date: 9/3/2018 
    Pet Name     :  Snickers
    Pet Species  :  Dog
    Pet Gender   :  Male
    Procedures   :  7
    Name				Price	QTY	Amount		Is Covered	Pct Covered	Amount Covered		Amount Due
             Rabies Shot               20.00                   1                true                0.75Distemper/Parvo Combo               45.00                   1               false                 0.0    Physical Therapy              100.00                   2                true                  .5           Microchip               19.00                   1               false                 0.0           Neutering              200.00                   1                true                  .8               X ray              200.00                   3                true                  .9      Overnight Stay              200.00                   2                true                  .8

  11. #36
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    make it so each output fits under the correct column
    Look at using format Strings with the correct widths. See the API doc of the Formatter class for how to write format Strings.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #37
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    question, i have to add totals of some numbers in the loop, am i able to do this within a loop or is there like a class or function or something i need to add to code?

  13. #38
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    Define the variables to hold the totals outside of the loop, and add to those variables inside of the loop.
    When execution exits the loop, the variables should hold the totals.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #39
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    Every line is not a number though, it is like every 6th line is a number i need to keep a total of, do i need to make an exception in the loop so that every like 6th line i hold that value?

  15. #40
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    If you use a counter for the lines, the modulus operator can be used to find every nth line.
    lineCnter % n would be 0 on every nth line.

    To see how it works, write a small simple program with a for loop that iterates several times the value of n and print out the value of the loop variable and the value of the loop variable modulus n
    If you don't understand my answer, don't ignore it, ask a question.

  16. #41
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    Is there any other way to do it? Like a more simple way? Only because the professor hasn't mentioned a counter to be needed at all.

  17. #42
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    That is about as simple a way as I know to find the nth iteration of a loop.

    Another way would be to have n read statements inside of the loop.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #43
    Junior Member tonya's Avatar
    Join Date
    Feb 2018
    Posts
    8
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Java read in + print to a file

    for example it doesn't come much easier than this to find every third iteration
    for(int i = 1; i < 10; i++) {
        if(i%3 == 0) {
            System.out.println(i);
        }
    }

  19. #44
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    @tonya There is a possible problem when a loop index starts at 1 vs 0. If the index is used to access a list or array it can miss the first element in the list.
    Can you think of ways to find the nth item with the index starting at 0?
    If you don't understand my answer, don't ignore it, ask a question.

  20. #45
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    With this code my program goes through the whole file but i still did not the format properly, but how would i add the the 2nd and 3rd i values?
    	while (inputScanner.hasNextLine()) 
     
    			{
    			for(int i=0;i<6;i++)
    			{
    			String line = inputScanner.nextLine();
    			ps.printf("%18s",line);
    			System.out.println(line);
     
     
    			} ps.printf("\r\n");
     
     
    			}

  21. #46
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    i still did not the format properly, but how would i add the the 2nd and 3rd i values?
    Please post a few lines of the program's output that shows the problem.
    Then create a sample of the desired output using the data from that output.
    Add some comments saying what needs to be changed.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #47
    Junior Member
    Join Date
    Sep 2018
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java read in + print to a file

    Done some reworking and got this now
    while (inputScanner.hasNextLine()) 
     
    			{
     
    				String Name, isCov;
    				int quantity;
    				double combinedCost,cost, amountCov, amountDue, pctCovered;
     
    				Name = inputScanner.nextLine();
    				System.out.print(Name);
     
     
    				cost = inputScanner.nextDouble();
    				System.out.print(cost);
    				inputScanner.nextLine();
     
    				quantity = inputScanner.nextInt();
    				System.out.print(quantity);
    				inputScanner.nextLine();
     
    				isCov = inputScanner.nextLine();
    				System.out.print(isCov);
     
    				pctCovered = inputScanner.nextDouble();
    				System.out.print(pctCovered);
    				inputScanner.nextLine();
     
    				combinedCost = cost + quantity;
    				amountCov = pctCovered * cost;
    				amountDue = combinedCost - amountCov;
     
     
    			ps.printf("%15s %15f %15d %15f %15s %15f %15f %15f\n",Name,cost,quantity,combinedCost,isCov,pctCovered,amountCov,amountDue);
     
    			}
    And my error message is
    in thread "main" java.util.NoSuchElementException
    	at java.base/java.util.Scanner.throwFor(Unknown Source)
    	at java.base/java.util.Scanner.next(Unknown Source)
    	at java.base/java.util.Scanner.nextDouble(Unknown Source)
    	at passarella.bcs345.hwk.vet.Standalonereport.main(Standalonereport.java:63)

  23. #48
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,381
    Thanks
    52
    Thanked 2,283 Times in 2,254 Posts

    Default Re: Java read in + print to a file

    in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Unknown Source)
    at java.base/java.util.Scanner.next(Unknown Source)
    at java.base/java.util.Scanner.nextDouble(Unknown Source)
    at passarella.bcs345.hwk.vet.Standalonereport.main(St andalonereport.java:63)
    That is what happens when nextDouble is called and there isn't any double value available to be read at line 63
    If you don't understand my answer, don't ignore it, ask a question.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. C# dll to read in JAva (Biometric finger print )
    By dominicevans06 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: July 20th, 2014, 03:25 AM
  2. Print to file with Java
    By suni.profile@gmail.com in forum What's Wrong With My Code?
    Replies: 9
    Last Post: May 30th, 2014, 12:07 PM
  3. Print to file with Java
    By suni.profile@gmail.com in forum Member Introductions
    Replies: 4
    Last Post: May 30th, 2014, 06:50 AM
  4. how to get the print preview for pdf file in java
    By sivanand in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 20th, 2013, 12:55 PM
  5. Java I/O File code; how to read/write file
    By ryu2le in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: September 18th, 2011, 05:51 PM