This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 7 years ago.
Hey Stack Overflow people, I'm having a bit of trouble understanding how writing and appending files works. Here is what I've been asked to do
• Save (append) the data for the contract to the text-based summary file (contracts.txt).
Each line in the file must hold the details for a single contract with the following information separated by spaces or tabs:
• Contract Date (today’s date - see technical details for format).
• Package (1=Small, 2=Medium and 3=Large)
• Data Bundle (1=Low, 2=Medium, 3=High and 4=Unlimited).
• Period in Months
• Allow international call from package minutes (Y or N)
• Reference Number.
• Monthly Charge (in pence).
• Client Name.
An example of the sort of file I'm looking to write would be this.
So far I have this code
public void appendFile()
{
PrintWriter output = null;
File confidential = new File("contracts.txt");
try
{
// create new file
FileWriter fw = new FileWriter(confidential, true);
output = new PrintWriter(fw);
}
catch (FileNotFoundException e) // Problem with file
{
System.out.println("Error: Problem creating the file! Program closing");
System.exit(0);
}
catch (IOException ex)
{
System.out.println("Error: Problem creating the file! Program closing");
System.exit(0);
}
output.print(date);
output.print(" ");
output.print(minutes);
output.print(" ");
output.print(data);
output.print(" ");
output.print(length);
output.print(" ");
output.print(international);
output.print(" ");
output.print(ref);
output.print(" ");
output.print(price);
output.print(" ");
output.print(name);
output.close();
}// end of main`
As you can see, my code is probably wrong and I'm not sure whether or not this method should even be in a seperate class or just stick the code for it in the main class? I appreciate the time it takes to go through my question and I hope someone can help me, as I'm currently about to rip my hair out in frustration of not understanding how to do it.
Add the statement output.print("\n"); at the end so that each record will be in separate line.
output.print(price);
output.print(" ");
output.print(name);
output.print("\n");
Related
public static void Replace_Record(String editTerm, String newItem, String newAmount, String newPrice){
String filepath="temp_Food_Item.txt";
String tempfile= "temp_Food_Item_temp.txt";
File oldFile= new File(filepath);
File newFile=new File(tempfile);
String item=""; String quantity=""; String price="";
System.out.println("working ");
try{
//System.out.println("working pt1");
FileWriter fw= new FileWriter(tempfile,true);
BufferedWriter bw= new BufferedWriter(fw);
PrintWriter pw= new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,/n]");
//System.out.println("working pt2");
while(x.hasNext()){
//System.out.println("working pt3");
item=x.next();
quantity=x.next();
price=x.next();
if(item.equalsIgnoreCase(editTerm)){
pw.println(newItem+","+newAmount+","+newPrice);
}
else{
//System.out.println("working pt4 ");
pw.println(item+","+quantity+","+price);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump=new File(filepath);
newFile.renameTo(dump);
}
catch(Exception e){
System.out.println("Error declared");
}
}
I don't understand where I went wrong but it is printing "error declared" so I debugged and found after working pt1 it stops and goes to catch please help?
Additional info includes:
I am making a database for a restaurant and I am inputting info in txt files in the sequence item_name,item_amount,item_price so I am taking my new values from, main and passing them to the method, in theory, it first duplicates a file until it comes to the strings I wanna remove and then replaces them and goes back to copy the strings from the real files. but every time I run this I get catch.
TIA
While I can't answer your question straight away, I can offer a few ideas.
First of, catch a more explicit exception, such as IOException, FileNotFoundException. It is generally good practice to have more explicit code and it's the first step towards improved error handling.
Also do something with it, for startes you can print it in your console and use that information to debug your program. It might tell you exactly what your error is and where it is.
hello everyone thanks for helping me through this problem but I have managed to fix it I took your tips and ran multiple types of exception till I found this was a file io error and I had a problem about naming the files so the compiler could not recognize which file I was calling other than that we Gucci thank you guys
Here is my code: https://pastebin.com/1Cmg5Rt8
The program asks the user for their name.
It then generates random math problems, and counts correct answers and incorrect answers.
The user is rewarded $0.05 for correct answers and penalized $0.03 for incorrect answers.
All of the above has been done.
I am stuck starting from here:
A file is created using their name.
The amount of answers they got correct/incorrect are recorded to a text file.
If a file under their name already exists, I must combine their results with the results of the ones on the file.
Example of existing text file:
Correct answers: 1
Incorrect answers: 0
Earnings: $0.05
If the user runs the program again and gets 1 correct answer, it must be updated like this:
Correct answers: 2
Incorrect answers: 0
Earnings: $0.10
Currently, instead of updating, it is being overwritten.
If I choose show stats at the beginning, this is the result (it uses the initialized values):
Correct answers:0
Incorrect answers: 0
Earnings: $0.00
I have spent hours trying to figure this out. I refuse to sleep until I solve this. Someone please help me. I will greatly appreciate it.
You need to read the name in /before/ you retrieve the stats, i.e. your main method should look like this:
public static void main(String[] args) {
validateCreditsResponse();
name();
retrieveStats();
menu();
saveStats();
}
Also, in this method, you need to also output a println like you do in the 'else' branch:
if (money > 0) {
outputfile.printf("Earnings: $%.2f", money);
// Add outputfile.println();
}
Finally, in this method you need to read in the data:
//Creates new text file for the user unless one already exists.
public static void retrieveStats() {
try {
writer = new FileWriter(userName + "Stats.txt", true);
outputfile = new PrintWriter (writer);
} catch (IOException e) {
}
}
You would start doing this with a FileReader, rather than a FileWriter.
For example in Java 8, like this:
//Reads existing text file for the user.
public static void retrieveStats() {
try (BufferedReader br = new BufferedReader(new FileReader(userName + "Stats.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher correctMatcher = Pattern.compile("Correct Answers:(.*)").matcher(line);
if (correctMatcher.matches()) {
correct = Integer.valueOf(correctMatcher.group(1));
}
// TODO complete other matchers
}
} catch (IOException e) {
}
}
I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:
import java.io.*;
import java.util.Scanner;
public class FilePractice {
public static void main(String[] args) {
//create a new File object
File myFile = new File("/home/christopher/Desktop/myFile");
try{
System.out.println("Would you like to create a new file? Y or N: ");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
myFile.createNewFile();
}
else
{
//do nothing
}
}catch(IOException e) {
System.out.println("Error while creating file " + e);
}
System.out.println("'myFile' " + myFile.getPath() + " created.");
}
}
I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.
Perhaps my syntax is wrong?
If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).
Here is the expanded attempt:
try {
System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
String fileName = input.nextLine();
input.nextLine();
System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
String userFilePath = input.nextLine();
File userFile = new File(userFilePath, fileName);
System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
String userChoice = input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
userFile.createNewFile();
//print for debug
System.out.println(userFile.getPath());
}
}catch(IOException e) {
System.out.println("Error while attempting to create file " + e);
}
System.out.println("File created successfully");
My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.
Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.
Changing input.nextLine() to input.next() solved the problem. The program was not reaching the if statement after asking the user if they were sure their entered path was the desired save point.
I also put in a simple else statement that printed out ("File not created") to verify that it was skipping it.
Anyway, question answered. :-)
I've got a loop that reads through a text file and outputs it, now I'm trying to get it to loop through, and write what's printed out into a text file as I want it to display as HTML. This is what I've got so far for this method:
public void hChoice()
{
File fbScores = new File ("P:/SD/Assignment1/fbScores.txt");
String line = "";
try {
Scanner scanScores = new Scanner(fbScores);
while(scanScores.hasNext())
{
line = scanScores.nextLine();
stringArr = line.split(":");
if(stringArr.length == 4)
{
System.out.println("<h1>" + stringArr[0]+" [" +stringArr[2]+"] |" + stringArr[1]+" ["+ stringArr[3]+" ]<br></h1> ");
PrintWriter out = new PrintWriter("P:/SD/Assignment1/HTMLscores.txt");
out.close();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
I've added the HTML tags in the print out and it prints it out fine, but I've tried several different methods to get it to print to a text file but none have worked. Pretty new to Java so any help would be much appreciated. Thankyou. :)
You've gotten your syntax and code wrong for writing to files.
Please Google and check the right syntax for writing to files using java. Plenty of resources available. You'll learn better if you try it yourself.
FYR, here is one: http://www.tutorialspoint.com/java/java_files_io.htm
I have the basics of my program finished.
The idea is that the user can specify a shape color width height etc. Upon inputting the data, constructors are called which create output, or there are other options which create output that the user can specify.
My goal is to get all of this output into a text file.
Currently I create a scanner for reading:
static Scanner input = new Scanner(System.in);
Then in my main driver method I create a Formatter:
public static void main(String[] args) {
Formatter output = null;
try{
output = new Formatter("output.txt");
}
catch(SecurityException e1){
System.err.println("You don't have" +
" write accress to this file");
System.exit(1);
}
catch(FileNotFoundException e){
System.err.println("Error opening or" +
" creating file.");
System.exit(1);
}
After each time I expect output I have placed this bit of code:
output.format("%s", input.nextLine());
And finally I close the file with
output.close()
The file is created but it is currently blank. I know I'm on the right track, because I've tried doing this:
output.format("%d", i);
where i is an integer of 0 and the file writes correctly.
However, I cannot seem to get it to work for an entire line, or for the output at all.
Please help!
I am not an expert but why can you not just use "FileWriter"?
Is it because you want to catch those exceptions to display useful information to the user?
Or have I misunderstood the question completely? - If so, sorry and just disregard this.
import java.io.FileWriter;
import java.io.IOException;
try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}