Problem writing on a .txt file using user input - java

I am writing a program that takes user input and displays it in a text file. I am having trouble having the input save on the file. Other similar questions have suggested to close the BufferedWriter, however I'm using a try-with-resource block which, as I understand it, should auto-close the resource. When I use fileWriter.close(); the text is saved however because it is being closed it will not be re-opened and I am given an IOException due to the stream being closed. How could I fix this issue?
Main Method
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class TextReader {
public static void main(String[] args) {
Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
try (Scanner scan = new Scanner(System.in);
BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Reader reader = new Reader(scan, path, fileWriter);
reader.menu();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reader Class
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
public class Reader {
Path path;
Scanner scan;
BufferedWriter fileWriter;
Reader(Scanner scan, Path path, BufferedWriter fileWriter) {
this.scan = scan;
this.path = path;
this.fileWriter = fileWriter;
}
public void menu() throws IOException {
String task;
do{
System.out.print("What would you like to do today?: ");
task = scan.nextLine();
switch(task){
case "1":
addData();
break;
case "6":
System.out.println("Goodbye!");
System.exit(0);
menu();
}
}while(!task.equals("6"));
}
void addData() throws IOException {
boolean cont = false;
do try {
System.out.print("Enter Name of Player: ");
String playerName = scan.nextLine();
System.out.print("Enter Number of Games Played: ");
int gamesPlayed = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Goals Made: ");
int goals = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Assists Made: ");
int assists = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Points Scored: ");
int points = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Saves Made: ");
int saves = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Shots Made: ");
int shotsOnGoal = Integer.parseInt(scan.nextLine());
fileWriter.write(
playerName + " " + gamesPlayed + " " + goals + " " +
assists + " " + points + " " + saves + " " + shotsOnGoal);
} catch(NumberFormatException e){
System.out.println("Enter Valid Input");
cont = true;
//insert finally clause to close fileWriter here
}while(cont);
}
}
IF fileWriter is closed in a finally clause after catching the NumberFormatException as indicated in the comment of the code, the following Exception is displayed
java.io.IOException: Stream closed
at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107)
at java.base/java.io.BufferedWriter.write(BufferedWriter.java:224)
at java.base/java.io.Writer.write(Writer.java:249)
at Reader.addData(Reader.java:74)
at Reader.menu(Reader.java:28)
at TextReader.main(TextReader.java:16)

Main
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class TextReader {
public static void main(String[] args) {
Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
try (Scanner scan = new Scanner(System.in);
BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Reader reader = new Reader(scan, path, fileWriter);
reader.menu();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reader Class
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
public class Reader {
Path path;
Scanner scan;
BufferedWriter fileWriter;
Reader(Scanner scan, Path path, BufferedWriter fileWriter) {
this.scan = scan;
this.path = path;
this.fileWriter = fileWriter;
}
public void menu() throws IOException {
String task;
do{
System.out.print("What would you like to do today?: ");
task = scan.nextLine();
switch(task){
case "1":
addData();
break;
case "6":
System.out.println("Goodbye!");
System.exit(0);
}
fileWriter.close();
}while(!task.equals("6"));
}
void addData() throws IOException {
boolean cont = false;
do try {
System.out.print("Enter Name of Player: ");
String playerName = scan.nextLine();
System.out.print("Enter Number of Games Played: ");
int gamesPlayed = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Goals Made: ");
int goals = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Assists Made: ");
int assists = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Points Scored: ");
int points = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Saves Made: ");
int saves = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Shots Made: ");
int shotsOnGoal = Integer.parseInt(scan.nextLine());
fileWriter.write(
playerName + " " + gamesPlayed + " " + goals + " " +
assists + " " + points + " " + saves + " " + shotsOnGoal);
cont = false;
} catch(NumberFormatException e){
System.out.println("Enter Valid Input");
cont = true;
}while(cont);
}
}

Related

scanner.close() Does not work when I use try/finally

import java.util.Scanner;
public class userInput
{
public static void main(String[]args){
try{
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int age = scanner.nextInt();
scanner.nextLine();
String text = scanner.nextLine();
System.out.println(name + "\n" + age + "\n" + text);
//scanner.close(); //it works here
}
finally{
scanner.close(); // does not work here"scanner cannot be resolvedJava(570425394)"
}
}
}
You have to define scanner before "try", so it's ok, now this is your code:
import java.util.Scanner;
public class userInput {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
try {
String name = scanner.nextLine();
int age = scanner.nextInt();
scanner.nextLine();
String text = scanner.nextLine();
System.out.println(name + "\n" + age + "\n" + text);
}
finally {
scanner.close();
}
}
}

How can I update specific parts of a text file in java?

This program is supposed to take in user input about a players name, assists, games played, scores, etc and print it in a .txt file. When the updateData(); method is called I want to be able to ask the user for the players name and what data they want to update, then i should be able to edit that specific part of the text. how could i go about doing this?
Main Class
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class TextReader {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
try (Scanner scan = new Scanner(System.in);
BufferedReader fileReader = new BufferedReader(new FileReader(String.valueOf(path)));
BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Reader reader = new Reader(scan, path, fileWriter, fileReader);
reader.menu();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reader Class
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class Reader {
Path path;
Scanner scan;
BufferedWriter fileWriter;
BufferedReader fileReader;
Reader(Scanner scan, Path path, BufferedWriter fileWriter, BufferedReader fileReader) {
this.scan = scan;
this.path = path;
this.fileWriter = fileWriter;
this.fileReader = fileReader;
}
public void menu() throws IOException {
String task;
do{
System.out.print("What would you like to do today?: ");
task = scan.nextLine();
switch (task) {
case "1":
addData();
break;
case "2":
updateData();
break;
case "6":
System.out.println("Goodbye!");
System.exit(0);
}
}while(!task.equals("6"));
}
void addData() throws IOException {
boolean cont;
DateTimeFormatter log = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String logTime = log.format(time);
do try {
System.out.print("Enter Name of Player: ");
String playerName = scan.nextLine();
System.out.print("Enter Number of Games Played: ");
int gamesPlayed = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Goals Made: ");
int goals = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Assists Made: ");
int assists = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Points Scored: ");
int points = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Saves Made: ");
int saves = Integer.parseInt(scan.nextLine());
System.out.print("Enter Number of Shots Made: ");
int shotsOnGoal = Integer.parseInt(scan.nextLine());
fileWriter.write(
playerName + " " + gamesPlayed + " " + goals + " " +
assists + " " + points + " " + saves + " " + shotsOnGoal + " (" + logTime + ") \n");
cont = false;
} catch(NumberFormatException e){
System.out.println("Enter Valid Input");
cont = true;
}while(cont);
}
void updateData() throws IOException {
System.out.print("Enter Player Name To Edit Data: ");
String playerName = scan.nextLine();
System.out.print("Enter Stat You Want To Change: ");
String stat = scan.nextLine().toLowerCase().trim();
if(fileReader.readLine().contains(playerName)){
String statSearch = fileReader.readLine();
}
}
}
}
Text File Format:
Name GP G A P S S%
Bobby 2 3 6 14 7 50
George 1 3 14 2 9 23
So if the user wanted to edit Name: George, type: Assists, the value 14 beside Georges name only would be edited
I have tried using an if statement to locate the string in the text and append it but I could not figure out how to only change the specified number without changing all the numbers found. Ex: if in the example above 14 is appended both would be changed instead of the one
If you are allowed for this project (i.e., not a school assignment), I recommend using JSON, YAML, or XML. There are too many Java libraries to recommend for using these types of files, but you can search "Java JSON library" for example.
First, need to address some issues...
It's not good practice to put Scanner scan = new Scanner(System.in); in a try-with-resource. It will auto-close System.in and won't be useable after being used in your Reader class. Instead, just do this:
Scanner scan = new Scanner(System.in);
Reader reader = new Reader(scan, path, fileWriter, fileReader);
Or, even better, don't pass it to the constructor, but just set scan to it in the constructor as this.scan = new Scanner(System.in);
Next, for fileReader, you can just initialize it similarly as you did for fileWriter:
BufferedReader fileReader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
Next, this line:
BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)
Every time this program is run, this line will overwrite the file to empty, which is probably not what you want. You could add StandardOpenOption.APPEND, but then this means you'll only write to the end of the file.
When you update data, you also have the issue that you'll need to "push" down all of the data that comes after it. For example:
Bobby 1 2 3 4 5
Fred 1 2 3 4 5
If you change the name Bobby to something longer like Mr. President, then it will overwrite the data after it.
While there are different options, the best and simplest is to just read the entire file and store each bit of data in a class (name, scores, etc.) and then close the fileReader.
Then when a user updates some data, change that data (instance variables) in the class and then write all of that data to the file.
Here's some pseudo-code:
class MyProg {
// This could be a Map/HashMap instead.
// See updateData().
public List<Player> players = new ArrayList<>();
public void readData(String filename) throws IOException {
Path path = Paths.get(filename);
try(BufferedReader fileReader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
// Read each Player (using specific format)
// and store in this.players
}
}
public void writeData(String filename) throws IOException {
Path path = Paths.get(filename);
try(BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
// Write each Player from this.players in specific format
}
}
public void updateData() {
// 1. Find user-requested Player from this.players
// 2. Update that specific Player class
// 3. Call writeData()
// If you are familiar with Maps, then it would be faster
// to use a Map/HashMap with the key being the player's name.
}
}
class Player {
public String name;
public int games;
public int goals;
//...
}

Counting words from user input text file

I am having trouble counting the amount of words in a given text file. Every time I input a text file name, the program returns "File not found". Here is the code I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Enter File name: ");
Scanner input=new Scanner (System.in);
String fileName= input.nextLine();
FileReader wordReader;
try {
wordReader=new FileReader(fileName);
BufferedReader reader=new BufferedReader(wordReader);
String cursor;
String content="";
int numberWords=0;
while((cursor=reader.readLine()) !=null) {
String []_words=cursor.split("");
for(String w: _words)
{
numberWords++;
}
}
System.out.println("Total words: "+ numberWords);
}catch (FileNotFoundException ex) {
System.out.println("File not found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You aren't splitting correctly. Split by " " instead of ""
String []_words=cursor.split(" "); //-------------> Add Space
This will give you the words instead of individual characters.
Also, you could just print _words.length instead of looping unnecessarily.
File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}

how to retrive data from a file

how should i retrive file of text1 to be used as a login information..
as i already enter the details in the registration part.. i would like to use the first name and staff id as a username and password for login part..
p/s: im so weak at coding..so please forgive my messy coding :)
here is my code.
import java.util.Scanner;
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileReader;
public class TestMyException12 {
static void clear() {
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter your last name:\n");
Scanner scan1 = new Scanner(System.in);
String text1 = scan.nextLine();
System.out.println("Enter your NRIC:\n");
Scanner scan2 = new Scanner(System.in);
String text2 = scan.nextLine();
System.out.println("Enter your Staff ID:\n");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
System.out.println("Enter your position:\n");
Scanner scan4 = new Scanner(System.in);
String text4 = scan.nextLine();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.write(text1);
writer.write(text2);
writer.write(text3);
writer.write(text4);
writer.newLine();
writer.close();
System.err.println("Your input data " + text.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else {
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter Password : ");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
if (scan.equals(text) && scan.equals(text3)) {
clear();
System.out.println("Access Granted! Welcome!");
} else if (scan.equals(text)) {
System.out.println("Invalid Password!");
} else if (scan.equals(text3)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Please register first!\n");
}
}
}
}
It's easy, make it like this :
package com.coder.singleton;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class TestMyException12 {
static void clear() {
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {
}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
StringBuilder sb = new StringBuilder();
String text = "";
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
text = input1.next();
sb.append(text + " ");
System.out.println("Enter your last name:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your NRIC:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your Staff ID:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your position:\n");
text = input1.next();
sb.append(text+ " ");
input1.close();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(sb.toString());
writer.newLine();
writer.close();
System.err.println("Your input data " + sb.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else {
String savedName = "";
String savedPassword = "";
try {
FileInputStream fis = new FileInputStream(new File("text1.txt"));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String word = "";
String [] arr = null;
while ((word = bufferedReader.readLine())!= null) {
arr = word.split("\\s+");
}
savedName = arr[0];
savedPassword = arr[2];
bufferedReader.close();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
String userName = input1.next();
System.out.println("Enter Password : ");
String password = input1.next();
if (userName.equals(savedName) && password.equals(savedPassword)) {
clear();
System.out.println("Access Granted! Welcome!");
}else if (userName.equals(savedName) && !password.equals(savedPassword)) {
System.out.println("Invalid Password!");
} else if (!userName.equals(savedName) && password.equals(savedPassword)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Please register first!\n");
}
}
}
}
the first,you should insert separator(like newLine) when save the register information to file text1,if not ,you can't distinguish information fields.for example:
fWriter = new FileWriter("d:\\tmp\\pass.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine(); //separator string
writer.write(text1);
writer.newLine();
writer.write(text2);
writer.newLine();
writer.write(text3);
writer.newLine();
writer.write(text4);
writer.newLine();
writer.close();
and then,you should retrieve the register information(just first name and staff) form file text1.txt
BufferedReader reader=new BufferedReader(new FileReader("text1.txt"));
String firstName = reader.readLine();
reader.readLine();
reader.readLine();
String passWord=reader.readLine();
final,compare input information with read information.
if (firstName.equals(text) && passWord.equals(text3)) {
System.out.println("Access Granted! Welcome!");
}
At Registration
You have to insert some delimiter (‘,’, ‘.’, ‘:’, ‘_’, ‘- ‘etc.…) at registration time.
Now Hear I am using “#” delimiter.
After insert that data and Delimiter.
Now At read time You have to split with That Delimiter you can access that data. in array
See Bellow code…
import java.util.Scanner;
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class TestMyException12
{
static void clear(){
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter your last name:\n");
Scanner scan1 = new Scanner(System.in);
String text1 = scan.nextLine();
System.out.println("Enter your NRIC:\n");
Scanner scan2 = new Scanner(System.in);
String text2 = scan.nextLine();
System.out.println("Enter your Staff ID:\n");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
System.out.println("Enter your position:\n");
Scanner scan4 = new Scanner(System.in);
String text4 = scan.nextLine();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.write("#");
writer.write(text1);
writer.write("#");
writer.write(text2);
writer.write("#");
writer.write(text3);
writer.write("#");
writer.write(text4);
writer.close();
System.err.println("Your input data " + text.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else
{
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter Password : ");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
String datafile = "";
try
{
FileReader fr = new FileReader("text1.txt");
int i;
while((i = fr.read()) != -1)
{
datafile = datafile+(char)i; // store all data into String obj from File
}
}
catch(Exception e)
{
System.out.println("Error In Login : "+e);
}
String[] userval = datafile.split("#"); // split that data and create part of that data
for(int i = 0 ; i < userval.length ; i++)
{
System.out.println(i+">>>>>"+userval[i]);
}
// userval[] is array that is store all data from that file into part
// after you can put any condition
//System.out.println(text+">>>>>"+userval[0]);
//System.out.println(text3+">>>>>"+userval[3]);
if(text.equals(userval[0]) && text3.equals(userval[3]))
{
clear();
System.out.println("Access Granted! Welcome!");
}
else
{
System.out.println("Please register first!\n");
}
}
}
}

java programming, writing to text files

how do i make this code write to the text file height.txt? it creates it but it doesnt write to it.
and it also compiles and says data is written to the file but there isnt any data when i open the file why is that?
import java.io.*;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
public class readinguserinput {
public static String gender;
public static int motherHeight;
public static int fatherHeight;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
try
{
FileWriter fw = new FileWriter("height.txt");
PrintWriter pw = new PrintWriter(fw);
System.out.println ("Enter gender");
gender = keyboard.next();
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
keyboard.nextLine();
while (motherHeight < 0)
{
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
}
System.out.println ("Enter father Height");
fatherHeight = keyboard.nextInt();
while (fatherHeight < 0)
{ System.out.println ("Enter Father Height");
fatherHeight = keyboard.nextInt();
}
pw.close();
}catch (IOException e){
System.out.println("file not found");
}
System.out.println("data written to the file");}}
The code never writes anything to the file. Try pw.print() and pw.println().
Change:
System.out...
To:
pw.out...
You are currently writing output to the console, not your PrintWriter
Your program just prints what you tell it to print. In this case you told it to print 'data written to the file', but you didn't tell it to actually write anything to the file. Your program lied to you, on your instructions.
As stated before. You haven't actually written anything to your file.
Try this
import java.io.*;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
public class readinguserinput {
public static String gender;
public static int motherHeight;
public static int fatherHeight;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
try
{
FileWriter fw = new FileWriter("height.txt");
PrintWriter pw = new PrintWriter(fw);
System.out.println ("Enter gender");
gender = keyboard.next();
pw.println("Gender: " + gender); // ***************
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
pw.println("motherHeight: " + motherHeight); // ***************
keyboard.nextLine();
while (motherHeight < 0)
{
System.out.println ("Enter Mother Height");
motherHeight = keyboard.nextInt();
pw.println("motherHeight: " + motherHeight); // ***************
}
System.out.println ("Enter father Height");
fatherHeight = keyboard.nextInt();
pw.println("fatherHeight: " + fatherHeight); // ***************
while (fatherHeight < 0)
{ System.out.println ("Enter Father Height");
fatherHeight = keyboard.nextInt();
pw.println("fatherHeight: " + fatherHeight); // ***************
}
pw.close();
}catch (IOException e){
System.out.println("file not found");
}
System.out.println("data written to the file");}}
Sample program to write a text file,
String content = "This is the content to write into file";
File file = new File("/data/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(content);
bufferedWriter.close();
Refer: How to write text file in Java ...

Categories

Resources