java programming, writing to text files - java

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 ...

Related

How can I question the user if they want to add a new record for a file?

My code simply asks the user to enter data for a file. I want to ask them every time if they want to add a new record before doing the process. Following is my code.
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Assign11 {
public static void main(String[] args) throws IOException{
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.nextLine();
System.out.println("Enter age.");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? "
+ "Type 'y' or 'n'.");
answer = keyboard.nextLine();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}
}
But the problem is that the question of adding a new record doesn't asked to user. So I was wondering what I did wrong and how I could fix it.
Here is quick fix for you. Please check following code.
You need to use next() in place of nextLine().
public static void main(String arg[]) {
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
try{
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.next();
System.out.println("Enter age.");
age = keyboard.nextInt();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? Type 'y' or 'n'.");
answer = keyboard.next();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}catch(IOException ex){
ex.printStackTrace();
}finally {
keyboard.close();
}
}
Hope this solution works.

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

Data entered is not writing to file

I am attempting to create and write to a .txt file so that another program can open and read it. The problem is that the entered data is not being written to the file created. It is a blank .txt document.
import java.util.Scanner;
import java. io.*; //import class for file input.
public class inventoryStock
{
public static void main(String args[]) throws Exception
{
//Declarations
String[] itemName = new String [10];
double[] itemCost = new double [10];
double[] inStockNumber = new double [10];
int counter = 0;
//End declarations
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
do
{
System.out.print("Enter item name");
pw.println();
itemName[counter] = input.next();
System.out.print("Enter item cost");
pw.println();
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
pw.println();
inStockNumber[counter] = input.nextDouble();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);
} //End of main method
} //End of InventoryStock class.
It seems that you didn't really write what you want to file. You can try the code below.
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
Two recommendations to you.
Since the size 10 is everywhere in your code. You'd better extract it to a single variable for better maintainability.
Please follow the naming convention of java. For your case, the first letter of class name should be capitalized. Use InventoryStock instead of inventoryStock.
The entire code is like below, hope it will help. Thx.
import java.util.Scanner;
import java.io.*; //import class for file input.
public class InventoryStock {
public static void main(String args[]) throws Exception {
int size = 10;
// Declarations
String[] itemName = new String[size];
double[] itemCost = new double[size];
double[] inStockNumber = new double[size];
int counter = 0;
// End declarations
Scanner input = new Scanner(System.in);
// Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
{
do {
System.out.print("Enter item name");
itemName[counter] = input.next();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
counter += 1;
} while (counter < size);
fw.flush();
}
fw.close();
System.exit(0);
} // End of main method
} // End of InventoryStock class.
You'll have to actually tell PrintWriter to write to file or else it won't do anything even though you grab the user's input with input.next(). Try something like this:
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw, true);
do
{
System.out.print("Enter item name");
itemName[counter] = input.next();
pw.write(itemName[counter]);
pw.println();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
pw.write(String.valueOf(itemCost[counter]));
pw.println();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.write(String.valueOf(inStockNumber[counter]));
pw.println();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);

File output with loop check and try catch block

Having a bit of trouble with file outputs and using try/catch. I'm trying to basically say that if the user inputs an existing filename, keep looping until valid filename is entered. However, i cant seem to get it to work. Any hints on where im going wrong? Tried moving the initial prompt around try block but wouldnt that make the scope only available in the try block? So essentially, i should have the prompt outside so its available to all the try/catch blocks? Not sure though.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class TestAccountWithException
{
public static void main(String[] args) throws IOException
{
// variable declaration
String fileName;
String firstName;
String lastName;
double balance;
int id = 1122;
final double RATE = 4.50;
Scanner input = new Scanner(System.in);
System.out.print("Please enter file name: ");
fileName = input.next();
File fw = new File(fileName);
try
{
// check if file already exists
while(fw.exists())
{
System.out.print("File already exists. Enter valid file name: ");
fileName = input.next();
fw = new File(fileName);
}
System.out.print("Enter your first name: ");
firstName = input.next();
System.out.print("Enter your last name: ");
lastName = input.next();
System.out.print("Input beginnning balance: ");
balance = input.nextDouble();
// pass object to printwriter and use pw to write to the file
PrintWriter pw = new PrintWriter(fw);
// print to created file
pw.println(firstName);
pw.println(lastName);
pw.println(balance);
pw.println(id);
pw.println(RATE);
pw.close();
// System.out.print("Run program? (1) Yes (2) No: ");
// cont = input.nextInt();
} catch (IOException e) {
e.printStackTrace();
}
} // end main
} // end class
You may prefer to use java.nio.file. With this java 7 package, you can use as
while(true) {
String fileName = input.next();
Path path = Paths.get(fileName);
if (Files.exists(path)) {
try {
// file exists
// your operations
} catch {
}
break;
} else {
// not found
fileName = input.next();
}
}

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.

Categories

Resources