PrintWriter & File in java - java

I wrote a program that will allow the user to store several memos in a file. I figured out how to use PrintWriter & File within Java but my issue is with my output. I can only enter one memo without issue & when I check the file on Notepad, only one memo is present. Here's the code:
import java.util.*;
import java.io.*;
public class MemoPadCreator{
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
boolean lab25 = false;
File file = new File("revisedLab25.txt");
PrintWriter pw = new PrintWriter (file);
String answer = "";
do{
while(!lab25){
System.out.print("Enter the topic: ");
String topic = input.nextLine();
Date date = new Date();
String todayDate = date.toString();
System.out.print("Message: ");
String memo = input.nextLine();
pw.println(todayDate + "\n" + topic + "\n" + memo);
pw.close();
System.out.print("Do you want to continue(Y/N)?: ");
answer = input.next();
}
}while(answer.equals("Y") || answer.equals("y"));
if(answer.equals("N") || answer.equals("n")){
System.exit(0);
}
}
}
Here's the output:
Enter the topic: I love food!
Message: Food is life!
Do you want to continue(Y/N)?: Y
Enter the topic: Message:
How do I go about changing it so the output will allow me to continue storing memos until I tell it to stop?

try {
Files.write(Paths.get("revisedLab25.txt"), ("the text"todayDate + "\n" + topic + "\n" + memo).getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling
}
Because you are looping with potentially multiple writes as the user adds input, you can wrap the writes in a Try-with-resources try block. The try-with-resources takes care of closing the file upon leaving the try block:
try(PrintWriter pw= new PrintWriter(new BufferedWriter(new FileWriter("revisedLab25.txt", true)))) {
do{
while(!lab25){
System.out.print("Enter the topic: ");
String topic = input.nextLine();
Date date = new Date();
String todayDate = date.toString();
System.out.print("Message: ");
String memo = input.nextLine();
pw.println(todayDate + "\n" + topic + "\n" + memo);
System.out.print("Do you want to continue(Y/N)?: ");
answer = input.next();
}
}while(answer.equals("Y") || answer.equals("y"));
}
catch (IOException e) {
//exception handling
}

Related

Filtering specific team from text file and displaying results

I want my program to allow a user to enter a team name and based on that name it will distribute the pertinent team information to the console for viewing. So far, the program allows the user to input a text file that contains unformatted team data. It then formats that data, stores it and prints the information to the console. It is at this point in my program where I want the user to be able to start her/his filtering based on a team name. I am not necessarily looking for an exact answer but some helpful tips or suggestions would be appreciated.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
System.out.println();
Scanner fileReader = null;
//A list to add results to, so they can be printed out after the parsing has been completed.
ArrayList<LineResult> results = new ArrayList<>();
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
while(fileReader.hasNext()) {
String line = fileReader.nextLine();// Read a line of data from text file
// this if statement helps to skip empty lines
if ("".equals(line)) {
continue;
}
String [] splitArray = line.split(":");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
//This section checks if each line has any corrupted data
//and then display message to the user.
if("".equals(splitArray[0]))
{
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}else if ("".equals(splitArray[1])) {
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}
try {
// Extract each item into an appropriate variable
LineResult result = new LineResult();
result.homeTeam = splitArray[0];
result.awayTeam = splitArray[1];
result.homeScore = Integer.parseInt(splitArray[2]);
result.awayScore = Integer.parseInt(splitArray[3]);
results.add(result);
} catch(NumberFormatException e) {
System.out.println(line + " > Home team score may not be a valid integer number ");
System.out.println(" or it may be missing");
System.out.println();
}
}else {
System.out.println(line + " > The field delimiter may be missing or ");
System.out.println(" wrong field delimiter is used");
System.out.println();
}
}
System.out.println();
System.out.println();
//Print out results
System.out.println("Home team Score Away team Score");
System.out.println("========= ===== ========= =====");
//Loop through each result printing out the required values.
//TODO: REQ4, filter results based on user requested team
try (BufferedReader br = new BufferedReader(new File(filename));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
if (values.length >= 3)
bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
}
}
for (LineResult result : results) {
System.out.println(
String.format("%-15s %1s %-15s %1s",
result.homeTeam,
result.homeScore,
result.awayTeam,
result.awayScore));
}
// end of try block
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
System.out.println();
}
}
//Data object for holding a line result
static class LineResult {
String homeTeam, awayTeam;
int homeScore, awayScore;}
}

Trying to take the input of a file, evaluate it and ouptut certain info

private void evaluateActionPerformed(java.awt.event.ActionEvent evt) {
Scanner sc = new Scanner("salesrep.txt");
while (sc.hasNext())
{
try {
readID = sc.next();
readFName = sc.next();
readLName = sc.next();
readSupplies = Double.parseDouble(sc.next());
readBooks = Double.parseDouble(sc.next());
readPaper = Double.parseDouble(sc.next());
readDistrict = sc.next();
readMOC = sc.next();
total = sum(readSupplies, readBooks, readPaper);
} catch (NumberFormatException e)
{
textArea.setText("Error: ");
}
if(total >= 8000)
{
try {
PrintWriter stars;
stars = new PrintWriter(new FileOutputStream(new File("stars.txt"), true));
String newLine = System.lineSeparator();
String newRecord = (readID + newLine + readFName + newLine + readLName + newLine + readSupplies + newLine + readBooks + newLine + readPaper + newLine + readDistrict + newLine + readMOC);
stars.append(newRecord);
stars.flush();
stars.close();
textArea.append("Sales Representatives Information Successfully Evaluated");
} catch (FileNotFoundException ex) {
Logger.getLogger(salesRepresentativeData.class.getName()).log(Level.SEVERE, null, ex);
textArea.setText("Error: File not found");
}
}
}
}
I am getting an error NoSuchElement upon hitting the second variable. Cant figure out why or how to get around it.
It's because of the way you initialize the Scanner object (sc). To read a file use:
Scanner sc = new Scanner(new File("salesrep.txt"));
The way you are doing it the Scanner.next() method will always see only one string which is of course "salesrep.txt". After all, the Scanner class does work against supplied Strings as well. You need to tell it that it is a file that you want to read.
On a side note, always remember, names can be Double-barrelled or Compound Surnames and both first and last names could contain two or more words (Otto Von Schnitzel or Jacques Le Roux) and there could be middle name or initial(s) applied as well. You need to consider this when using the Scanner.next() method since this method only retrieves the next space delimited token.

Troubles reading a single character from a text file

I'm writing an "app" that takes in time input from the user and stores the hours and the minutes separately for each day in a text file (giving a result that looks like:
day 1: 8h 45min
day 2: 8h 43min
... )
the idea behind it is to use this data for multiple stuff, like calculating the average time, or just accessing the time at any day, but I haven't reached that stage yet, I'm having troubles doing the simplest stuff like reading the hour and printing it.
here's the code
import java.util.Scanner;
import java.io.*;
public class TimeInput {
public static void main(String[] args) {
write();
read();
}
static void write() {
int dayOfMonth = 1;
String fileName = "time.txt";
int[] time = new int[2];
String timeDisplay;
Scanner s = new Scanner(System.in);
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while (dayOfMonth <=31) {
System.out.println("Day " + dayOfMonth);
System.out.print("Enter hour: " + "__" + "h\r");
System.out.print("Enter hour: ");
time[0] = s.nextInt();
System.out.print("Enter minutes: " + "__" + "min\r");
System.out.print("Enter minutes: ");
time[1] = s.nextInt();
timeDisplay = ("\n"+ "day " + dayOfMonth + ": " + time[0] + "h " + time[1] + "min");
bufferedWriter.write(timeDisplay);
bufferedWriter.newLine();
dayOfMonth++;
if (time[0] == 0 && time[1] == 0) {
bufferedWriter.close();
dayOfMonth = 32; // break
}
}
}
catch (IOException ex) {
System.out.println(
"Error writing to file '" + fileName + "'");
}
}
static void read() {
String fileName = "time.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
char h = line.charAt(7);
System.out.println(h);
}
bufferedReader.close();
}
catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" + fileName + "'" );
}
catch (IOException ex) {
System.out.println(
"Error reading file '" + fileName +"'");
}
}
}
I keep getting a String out of bounds exception and I don't understand why
You need to check empty string before char operation.
while ((line = bufferedReader.readLine()) != null) {
if("".equals(line)){
continue;
}
char h = line.charAt(7);
System.out.println(h);
}
Buffered Writer also saved enter key presses between your input. So to eliminate that enter presses add dummy readLine statement between each line read.
line=bufferedReader.readLine();
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
char h = line.charAt(7);
System.out.println(h);
line=bufferedReader.readLine();
}
Take a look to the last loop.
Put a breakpoint and see what happen. Maybe the ArrayIndexOutBoundExceptions happens cuz youre trying to read more that one character and this cant be possible. Take a look to this url to see how to read a txt with bufferedReader.
http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Hope this help.

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));

Java program will not output to file

This is a very basic program for Uni which writes user data to a file. I have followed the instructions clearly yet it does not seem to output the data to a file. All it does is create an empty file. I'm using Ubuntu, if this makes a difference.
import java.util.Scanner;
import java.io.*;
/**
This program writes data to a file.
*/
public class FileWriteDemo
{
public static void main(String[] args) throws IOException
{
String fileName; // File name
String friendName; // Friend's name
int numFriends; // Number of friends
// Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Get the number of friends
System.out.print("How many friends do you have? ");
numFriends = keyboard.nextInt();
// Consume the remaining new line character
keyboard.nextLine();
// Get the file name
System.out.print("Enter the filename: ");
fileName = keyboard.nextLine();
// Open the file
PrintWriter outputFile = new PrintWriter(fileName);
// Get data and write it to a file.
for (int i = 1; i <= numFriends; i++)
{
// Get the name of a friend
System.out.print("Enter the name of friends " +
"number " + i + ": ");
friendName = keyboard.nextLine();
}
// Close the file
outputFile.close();
System.out.println("Data written to the file.");
}
}
You are creating a PrintWriter instance but nothing is being written to it.
Perhaps you meant to include outputFile.println(friendName) inside the for-loop?
Try
for (int i = 1; i <= numFriends; i++)
{
// Get the name of a friend
System.out.print("Enter the name of friends " +
"number " + i + ": ");
friendName = keyboard.nextLine();
outputFile.println(friendName);
}

Categories

Resources