Having difficulty with outputting file - java

So we've started learning some file handling and Im currently writing some code to output and file to text, when that file has been written I need to open it again and extract information and then output that information to another file, the problem Im having is when I go to extract that information it seems to overwrite both files and they both end up blank. The first part of the code in my switch statement works, but I can't seem to figure out where my error is, any help would be greatly appreciated! =]
So here is my handler for the lines
public class AssignementHandler {
private String studentNo;
private String studentName;
private int result1;
public String getstudentNo() {
return studentNo;
}
public String getstudentName() {
return studentName;
}
public int getResult1() {
return result1;
}
public static boolean checkStringForDigits(String s){
for(int i = 1; i < 8; i++){
if(!Character.isDigit(s.charAt(i)))
return false;
}return true;
}
public void lineSeperate(String line){
//read each char until I find a digit
int i = 0;
while(!Character.isWhitespace(line.charAt(i)))//while it is not a space
i++; //keep going
//stops when I find a space - so this is the start of the name
studentNo = line.substring(0, i).trim();
int nameStart = i;
while(!Character.isDigit(line.charAt(i)))//while it is not a space
i++; //keep going
studentName = line.substring(nameStart, i).trim();
result1 = Integer.parseInt(line.substring(i).trim());
}
and then my tester is as follows
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class studentTester {
public static void main(String[] args) throws IOException, FileNotFoundException, RuntimeException {
#SuppressWarnings("resource")
Scanner keyIn = new Scanner(System.in);
int option;
do{
System.out.println("\nStudent Application\n*******************");
System.out.println("1. Enter Student Details");
System.out.println("2. Write test marks to results.txt and highest.txt");
System.out.println("3. Display contents of any file on screen");
System.out.println("0. Quit\n*******************");
System.out.print("\nPlease enter option: ");
option = keyIn.nextInt();
String studentNo;
String studentName;
int result1;
PrintWriter studentOUT = new PrintWriter(new FileWriter("student.txt"));
AssignementHandler handlelines = new AssignementHandler();
switch (option) { //start switch
case 1: //add Student Details - Menu Option 1
char userResponse = 'y';
System.out.print("\nOption Selected - Enter Student Details" + "\n------------------\n");
keyIn.nextLine(); //clear buffer of option 1
System.out.print("Please enter student number in the format L0000000: ");
studentNo = keyIn.nextLine();
if(studentNo.length() !=9){
System.out.println("Incorrect Length: Must have 1 Letter and 8 Numbers!");
continue;
}
else if(!(Character.isLetter(studentNo.charAt(0)))){
System.out.println("Student Number must begin with a Letter!");
continue;
}
else if(!AssignementHandler.checkStringForDigits(studentNo)){
//if it returns false
System.out.println("Incorrect Format, Student Number Must Have 8 numbers!" );
continue;
}
System.out.print("Please Enter Student Name: ");
studentName = keyIn.nextLine();
System.out.print("Please Enter Result - (1): ");
result1 = keyIn.nextInt();
studentOUT.println(studentNo + " " + studentName + " " + result1);
do{
System.out.print("Do you want to add another student?: \n" +
"(Y) or (N)");
userResponse = keyIn.next().charAt(0);
keyIn.nextLine(); //clear buffer
}while (userResponse != 'n');
studentOUT.close();
System.out.println("Student Records have been written successfully to - student.txt - !");
break;
////////////////////////////////////////////////////////////////////////////////////////////
case 2: //write test marks to results.txt and highest.txt - Menu Option 2
System.out.print("\nOption Selected - Write Files" + "\n------------------\n");
System.out.println("Files have been written successfully!");
keyIn.nextLine(); //clear buffer of option 2
Scanner studentsIN = new Scanner(new File("student.txt"));
try{
PrintWriter resultsOut = new PrintWriter( new FileWriter("results.txt", true));
try{
while(studentsIN.hasNextLine()){
String line = studentsIN.nextLine(); //read the next line
//System.out.println(line); //for testing
//process the line
handlelines.lineSeperate(line);
String studentNumber = handlelines.getstudentNo();
//String studName = handlelines.getstudentName();
int resultIN = handlelines.getResult1();
//write to the file
resultsOut.printf(studentNumber+""+resultIN+"");
}//end while
}//inner try - files are open and being processed
finally{
studentsIN.close();
resultsOut.close();
}
}//end outer try
catch(FileNotFoundException ex){
System.out.println(ex);
}
catch(RuntimeException ex){
System.out.println(ex);
}
catch(IOException ex){
System.out.println(ex);
}
break;
////////////////////////////////////////////////////////////////////////////////////////////
case 0:
System.out.println("Results Application shutting down...\n******** Goodbye ********"); //quit program
break;
default:
System.out.println("Invalid option entered ");
}//end switch
}while (option != 0); //end user interface
}//end main method
}//end class studentTester
it just seems to write two blank files without extracting the the information I need, not sure what I am doing wrong here as Im following some previous examples we did in class.

Related

writing files in java from user input

I'm trying to write a program which will take user input from a list of options then either:
write to a file
alter an existing file or
delete a file.
At the moment I'm stuck on just writing to the file from the user input. I have to use regex notation for each of the users input as seen in the snippet. Any help or guidance on what i could do will be highly appreciated, and yes there are a lot of errors right now. Thanks!
import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
private UserInput[] list;
class Input {
public static void main(String[] args) {
Scanner in = (System.in);
string Exit ="False";
System.out.println("person details");
System.out.println("");
System.out.println("Menu Options:");
System.out.println("1. Add new person");
System.out.println("2. Load person details ");
System.out.println("3. Delete person Entry");
System.out.print("Please select an option from 1-5\r\n");
int choice = in.nextLine();
if (choice == 1)
system.out.println("you want to add a new person deails.");
AddStudnet();
else if (choice == 2){
system.println("would you like to: ");
system.println("1. Load a specific entry");
system.println("2. Load ");
}
//Error checking the options
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int input = Integer.parseInt(br.readLine());
if(input < 0 || input > 5) {
System.out.println("You have entered an invalid selection, please try again\r\n");
} else if(input == 5) {
System.out.println("You have quit the program\r\n");
System.exit(1);
} else {
System.out.println("You have entered " + input + "\r\n");
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your input!\r\n");
System.exit(1);
}
}
}
//Scanner reader = new Scanner(System.in);{ // Reading from System.in
//System.out.println("Please enter your name: ");
//String n = reader.nextLine();
//}
// File file = new File("someFile.txt", True);
// FileWriter writer = new FileWriter(file);
// writer.write(reader);
// writer.close();
public static void addPerson(String args[]) throws IOException{
class input Per{
scanner in = new scanner (system.in);
system.out.print("Please enter you Name: ");
String name = in.nextLine()
final Pattern pattern = Pattern.compile("/^[a-z ,.'-]+$/i");
if (!pattern.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid String");
//String Name = regex ("Name")
//regex below for formatting
system.out.println("Please enter your Job title:");
//String CourseNum = regex ("JobTitle");
system.out.println("Please enter your Town:");
//String Town = regex("Town");
system.out.println("Please enter your postcocde:");
//String postcocde = regex("postcocde");
system.out.println("Please enter your street:");
//String Street = regex ("Street");
system.out.println("Please enter your House Number:");
//String HouseNum = regex ("HouseNum");
}
}
//public static void
Is not clear that you look for " i'm stuck on just writing to the file"
here exemple on how to create/write to a file
String export="/home/tata/test.txt";
if (!Files.exists(Paths.get(export)))
Files.createDirectory(Paths.get(export));
List<String> toWrite = new ArrayList();
toWrite.add("tata");
Files.write(Paths.get(export),toWrite);
look at java tm
https://docs.oracle.com/javase/tutorial/essential/io/file.html
lio

An array of string causing my program not to continue to run after an if-else statement - java

I am creating a simple program that gets an input from a user and outputs to .txt file. I have made some changes to my code so that whenever a user enters a variation of 'quit', 'Quit', or 'QUIT' it will break, else it will continue as normal. However when I run and enter data as normal it is not continuing as normal and stopping. Also, how would I display a printline so that when a user does type 'Quit' it would say for example
System.out.println("You have quit!");
My Code
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.nio.file.*;
public class JavaProject {
private static char[] input;
public static void main(String[] args) {
//variables
int hrs, mins;
String gamerName, gamerReport;
int gameCount;
int errorCount;
//Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
int[] minutesPlayed = new int [100];
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
//formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
//User enters either their name or quit. Entering a name will move on to next part
for ( ; ; )
{
System.out.print("Enter your Name. If you do not wish to proceed, enter 'Quit' to quit.");
System.out.println(" ");
gamerName = Scan.nextLine();
if ("Quit".equals(gamerName))
{
break;
}
for(int b = 1; b < 100; b++ ) { //this is making the code loop 100 times
//user is given an example of input format
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println("FALSE DATA FORMAT WILL CAUSE ERROR");
System.out.println(" ");
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport = null; // an array of string
//splitUpReport = gamerReport.split(":"); // split the text up on the colon
//gets input, if "quit" then break
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equals("quit"))
{
break;
}
if (gamerReport.equals("Quit"))
{
break;
}
if (gamerReport.equals("QUIT"))
{
break;
}
else
{
splitUpReport = gamerReport.split(":");
}
System.out.println("You have quit!");
}
int i = 0;
//copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
//output to file using a PrintWriter using a FileOutPutStream with append set to true within the printwriter constructor
//
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
//writer.println("Games Played: " + splitUpReport);
//writer.println("Total Achievement: " + highScores);
//writer.println("Total Time: " + minutesPlayedS%60);
writer.println();
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
System.out.println("Goodbye!");
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
my code issue
//gets input, if "quit" then break
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equals("quit"))
{
break;
}
if (gamerReport.equals("Quit"))
{
break;
}
if (gamerReport.equals("QUIT"))
{
break;
}
else
{
splitUpReport = gamerReport.split(":");
}
System.out.println("You have quit!");
}
You should change your if to else if. Otherwise your else is only regarding the third if. You can also use a single if with equalsIgnoreCase. This matches quit, Quit or QUIT.
To print a message, before each break, insert your System.out.println("You have quit!");
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equalsIgnoreCase("quit")) {
System.out.println("You have quit!");
break;
}
splitUpReport = gamerReport.split(":");
gameNames[count] = splitUpReport[0];
highScores[count] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[count] = Integer.parseInt(splitUpReport[2].trim());
}
You also have another option, maybe more in-line with what you were trying to do.
// ignore the for loop
gamerReport = Scan.nextLine();
if (gamerReport.equalsIgnoreCase("quit")) {
System.out.println("You have quit!");
return;
}
splitUpReport = gamerReport.split(":");
You should also not comment one of your scans:
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
//gamerReport = Scan.nextLine();
And your writer should use splitReport:
writer.println("Game: " + splitUpReport[0] + ", score= " + splitUpReport[1] + ", minutes played= " + splitUpReport[2]);

My bufferedread only reading the first line of my file?

The bufferedreader I have used in my code seems to read only the first line of the code. Can some one help me solve the problem, I've been trying for a long time.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;
public class Task2Recipe {
private static String Ingredient;
private static String ServingNumber;
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'");
String choice = user_input.next();
user_input.nextLine();
if (choice.equals("write")) {
write();
}
if (choice.equals("read")) {
read();
}
}
public static void write() {
try {
FileWriter Task2Recipe = new FileWriter("P:/Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedWriter recipe = new BufferedWriter(Task2Recipe);
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the name of your recipe, if more than 1 word, seperate your words with a dash");
String RecipeName = user_input.next();
recipe.write("Name of recipe: " + RecipeName);
recipe.newLine();
System.out.println("Please enter the number of people your recipe serves");
ServingNumber = user_input.next();
recipe.write(ServingNumber);
recipe.newLine();
System.out.println("Please enter the name of your first ingredient, the quantity and units separated with a comma");
Ingredient = user_input.next();
recipe.write(Ingredient);
recipe.newLine();
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
String choice2 = user_input.next();
user_input.nextLine();
while (choice2.equals("yes")) {
System.out.println("Please enter the name of your ingredient, the quantity and units separated with a comma");
Ingredient = user_input.nextLine();
recipe.write(Ingredient);
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
choice2 = user_input.next();
user_input.nextLine();
}
recipe.close();
} catch (Exception e) {
System.out.println("A write error has occured");
}
}
public static void read() {
try {
Scanner user_input = new Scanner(System.in);
FileReader file = new FileReader("P:Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedReader buffer = new BufferedReader(file);
System.out.println("Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'");
String choice3 = user_input.next();
user_input.nextLine();
while (choice3.equals("yes")) {
String line;
System.out.println("Please enter the new serving number");
int NewServingNumber = user_input.nextInt();
int counter = 0;
while ((line = buffer.readLine()) != null) {
counter++;
if (counter == 2) {
}
if (counter > 3) {
String[] word = Ingredient.split(",");
int Quantity = Integer.parseInt(word[1]);
int ServingNumberInt = Integer.parseInt(ServingNumber);
int Multiplier = ServingNumberInt / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
System.out.println(line);
buffer.close();
}
} catch (Exception e) {
System.out.println("A read error has occured");
}
}
}
My input was:
applep - for the recipe name
10 - for serving number
apple,10,apples - for the ingredient, I only added 1 ingredient.
When I read and read my file and change the recipe servinging number, it doesn't not work and gives in an 'read error'. In addition, to test the problem, I printed the variable 'line' and it only seems to read the first line.
Thanks in advance!
You have two independent cases - one for reading and one for writing. If in one case, you assign values ​​to variables, it does not mean that in other case you can read them. Also the counter is not set correctly. Try this code -
while((line = buffer.readLine()) !=null) {
counter++;
if (counter == 3) {
//String[]word = Ingredient.split(",");
String[]word = line.split(",");
int Quantity = Integer.parseInt(word[1]);
//int ServingNumberInt = Integer.parseInt();
int Multiplier = NewServingNumber / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
it gives -
Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'
read
Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'
yes
Please enter the new serving number
10
Your new quantity is 10

How can I rename a file with the name of the original and delete the original file?

import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWritingApp{
public static void main(String[] args) {
String inputFilename = "marks.txt"; // It expects to find this file in the same folder as the source code
String outputFilename = "fakemarks.txt"; // The program will create this file
PrintWriter outFile;
String name,choice;
int mark1,mark2;
boolean flag=false;
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add or find a student?");
try {
outFile = new PrintWriter(new FileWriter(outputFilename),true); // create a new file object to write to
File file = new File(inputFilename); // create a file object to read from
File file1 = new File(outputFilename);
Scanner scanner = new Scanner(file); // A scanner object which will read the data from the file passed in.
choice= input.nextLine();
switch(choice){
case "f":
System.out.println("Enter a name:");
name=input.nextLine();
while (scanner.hasNextLine()) { // This will loop until there are no more lines to read
String line = scanner.nextLine();
if(line.contains(name)){
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
line=name+", " + mark1 +", "+ mark2;
outFile.println(line);
flag=true;
} else {
outFile.println(line);
}
}
if(flag==false){
System.out.println('"'+name+'"'+" wasn't found");
}
break;
case "a":
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
outFile.println(line);
}
System.out.println("Enter a name:");
name=input.nextLine();
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
outFile.println(name+", " + mark1 +", "+ mark2);
break;
}
***scanner.close();
outFile.close();
if(file1.renameTo(file)){
System.out.println("rename succesful");
} else {
System.out.println("rename unsuccesful");
}
if(file.delete()){
System.out.println("delete succesful");
} else {
System.out.println("delete unsuccesful");
}***
}catch (IOException e) {
e.printStackTrace();
}
}
}
What I am having a problem with is that every time I run the program it returns false for changing the name of the new file to the original file and deleting the original file itself. I would appreciate if someone posted some code to solve this. I have highlighted the code that outputs feedback above.

Trying to add info (highscorelist) to a .txt file + sorting, without removing existing data

This is for a uni-assignment.
So, where do I begin?
The task: The assignment is to make a high schore-list that is a external .txt-file. The .txt-file can only have 5 different top scores, that means if I add a high score that's higher than the 5th place-high scorer that one needs to be deleted and replaced with the new high score.
If you click the class-name you'll get redirected to a pastie-link that includes the code.
The problem(s): I can not for the life of me get the code to add text without removing current text. The current statement of the code is maybe a wrong way of dealing with the problem, I dont know. I've tried several ways and none seemed to work for me (Or I was doing wrong). Sorting the list should not be a problem since I've done that in a recent assignment.
Anyways, enough chit-chat, let's get to business.
My main:
public class main {
public static void main(String[] args) {
menu menu = new menu();
menu.display();
}
}
My menu:
import java.util.*;
public class menu {
highscores highscores = new highscores();
private Scanner input = new Scanner(System.in);
public void display() {
System.out.println("Make your selection!");
System.out.println("Select an option: \n" + " 1) Insert new score\n"
+ " 2) Print list\n" + " 3) Reset list \n" + " 4) Quit\n ");
int selection = input.nextInt();
input.nextLine();
switch (selection) {
case 1:
highscores.enterScore();
break;
case 2:
highscores.printList();
break;
case 3:
highscores.resetList();
break;
case 4:
System.out.println("Exiting program...");
System.exit(1);
default:
System.out.println("Try Again!");
break;
}
}
}
My high score-list
import java.io.*;
import java.util.*;
public class highscores {
public void enterScore() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the players name!: ");
String name = scan.nextLine();
System.out.println("Enter the players score!: ");
String score = scan.nextLine();
System.out.println("Player " + name + " got: " + score
+ " points. Great job!");
try {
File file = new File("HighScores.txt");
PrintWriter writer;
writer = new PrintWriter(file);
writer.println("Player name: " +name +" - " +"Player score:" +score);
writer.close();
} catch (Exception e) {
System.out.println("Error #1");
}
}
public void printList() {
try {
File file = new File("Highscores.txt");
Scanner scanner;
if (file.exists()) {
scanner = new Scanner(file);
for (int i = 0; i < 5; ++i) {
String line = scanner.nextLine();
System.out.println(line);
}
} else {
System.out.println("Error #2");
}
} catch (Exception e) {
System.out.println("Error #1");
}
}
public void resetList() {
try {
File file = new File("Highscores.txt");
PrintWriter writer;
writer = new PrintWriter(file);
for (int i = 0; i < 5; ++i) {
writer.println("Player name: x - Player score: x ");
}
writer.close();
} catch (Exception e) {
System.out.println("Error #1");
}
}
}
Is there ANY way of saving this code and using it for this assignment?
The problem(s): I can not for the life of me get the code to add text without removing current text.
Use FileWriter(File file, boolean append) and wrapper it within the PrintWriter(Writer out).
FileWriter(File file, boolean append)'s JavaDoc:
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file
rather than the beginning
Update your code:
PrintWriter writer;
writer = new PrintWriter(file);
to:
PrintWriter writer;
writer = new PrintWriter(new FileWriter(file, true));

Categories

Resources