java while loop try catch, cant print to a new line - java

Having an issue here, I need this loop to print new lines of code to a file until but what it does is print 1 line then fails on the second time round,
Can never get it to print to another line, below is code
public class study {
public static void main(String[] args) throws IOException{
BufferedWriter post = null;
File file = new File("text.txt");
if(!file.exists()){
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
post = new BufferedWriter(fileWriter);
try {
while(promptUser){
System.out.println("enter age "); //get age
Scanner getage = new Scanner(System.in);
int age= getage.nextInt();
if(age <20 || age>50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); //get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
post.write(age + "\t"); <===== fails here on second run
post.write(name + "\t");
post.write(email + "\t");
post.newLine();
post.close();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if(option.equalsIgnoreCase("quit")){
System.out.println("goodbye!");
System.exit(0);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

post.write(age + "\t");
post.newLine();
post.write(name + "\t");
post.newLine();
post.write(email + "\t");
post.newLine();
//remove post.close(); from here
Now it may solve Your problem

Replace post.close(); with post.flush(); and you should be fine.
Close the stream when the exit condition is entered.

FIXED IT GUYS
I needed to move the FileWriter line out of the TRY
import java.io.*;
import java.util.*;
public class study {
public static void main(String[] args) throws IOException {
BufferedWriter post = null;
File file = new File("text.txt"); //create file
if (!file.exists())
{
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
try {
while (promptUser) {
post = new BufferedWriter(fileWriter);
System.out.println("enter age "); // get age
Scanner getage = new Scanner(System.in);
int age = getage.nextInt();
if (age < 20 || age > 50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); // get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
//send data to file
post.write(age + ";");
post.write(name + ";");
post.write(email + ";");
post.newLine();
post.flush();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if (option.equalsIgnoreCase("quit")) {
System.out.println("goodbye!");
post.close(); // close file upon quitting
System.exit(0);
}
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Related

How do i put a Try-catch statement looking for a file in a loop?

I need to put my searching of the file in my readData() method in a loop that catches the fine not found exception then loops to prompt the user again for the file name until the correct one is entered. Once the proper file name is entered, then the return values pass to the other methods to continue the code.
I have tried putting the block of code into a do-while method but it results in a infinite loop. I need assistance with the semantics of this.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
I am expecting this to explain "File not found!" then prompt again for the file name until the correct one is entered. However it only does the try-catch once and then attempts to return the inputValues return value. This causes the program to crash.
I have tried do while loop. But it ends up in an infinite loop
package weightedavgdataanalyzer;
import java.io.*;
import java.util.*;
public class WeightedAvgDataAnalyzer {
public static void main(String[] args) {
ArrayList<Double> inputValues = readData();
double weightedAvg = calcWeightedAvg(inputValues);
printResults(inputValues, weightedAvg);
}
private static void printResults(ArrayList<Double> inputValues, double weightedAvg) {
System.out.print("Enter output file name: ");
Scanner input = new Scanner(System.in);
String outputFile = input.nextLine();
try {
PrintWriter writer = new PrintWriter(outputFile);
writer.print("The weighted average of the numbers is " + weightedAvg + ", when using the data ");
for (int i = 2; i < inputValues.size(); i++) {
writer.print(inputValues.get(i) + ", ");
}
writer.println("where " + inputValues.get(0)
+ " is the weight used, and the average is computed after dropping the lowest "
+ Integer.valueOf((int) inputValues.get(1).doubleValue()) + " values.");
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static double calcWeightedAvg(ArrayList<Double> inputValues) {
double sum = 0;
double average;
double weight = inputValues.get(0);
int toDrop = Integer.valueOf((int) inputValues.get(1).doubleValue());
ArrayList<Double> newList = new ArrayList<>();
for (int i = 2; i < inputValues.size(); i++) {
newList.add(inputValues.get(i));
}
Collections.sort(newList);
for (int i = (toDrop); i < newList.size(); i++) {
sum += weight * newList.get(i);
}
average = sum / (newList.size() - toDrop);
return average;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
}
Move the initialization of File file = new File(inputFileName); inside the loop as well as the "ask for new file name line". And last step is to also check if the file is an directory. You can't read directories with a Scanner, but file.exists() will still return true
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
File file;
System.out.print("Enter the name of the input file: ");
do {
inputFileName = input.nextLine();
file = new File(inputFileName);
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
} while (!file.exists() && !file.isDirectory());
return inputValues;
}
The other answers have not addressed that it is bad practice to control the flow of your code using catch and exception. You should reserve using your catch block for typically printing your errors or logging them.
I moved the logic of asking for the file into a loop that does not depend on an exception to correctly execute and placed it into a reusable method.
Here is what this change would look like:
ArrayList<Double> inputValues = new ArrayList<>();
double value;
File file = promptForFile(); //Condensed into a clean reusable single line of code
try {
Scanner input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //Or log the error
}
And the method you can reuse anywhere for a new prompt:
public static File promptForFile()
{
System.out.print("Enter the name of the input file: ");
Scanner input = new Scanner(System.in);
String inputFileName = input.nextLine();
File file = new File(inputFileName);
while(!file.exists() && !file.isDirectory())
{
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
inputFileName = input.nextLine();
file = new File(inputFileName);
}
return file;
}
Now the logic of your code is separated from searching for the file and the code is extremely reusable and readable.
This couldn't be done before since you had two different logics mixed intertwined.
File myFile = new File("myFile.txt");
while(!myFile.exists()){
//re-enter filename and instantiate myFile as a new object using it as the argument
}
could just check whether the file exists in a loop like so before using it. The issue with looping for the FileNotFoundException is that your writer is what throws that, so you would have to constantly instantiate the writer and check whether the exception is thrown before possibly looping again, which isn't ideal.
The problem is when the exception is caught, you never ask for a new file name, so you are running the code on the same faulty file path over and over again. To fix this, just move this code block:
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
inside the loop.
You may also want to eliminate a condition on your loop, and instead add a return; at the end of your try block.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
while (true) {
try {
// Get response in the loop, instead of one time-only
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
// Add your return statement here to get rid of the conditional
// loop.
return inputValues;
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
}
You can take input and can return once file is found or else can keep recording error message
public File getFile(){
while(true) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the name of the input file: ");
File file = new File(System.in);
if (file.exists()) {
return file;
}else{
System.out.println("File not found! Please try again ");
}
}
}
}
private List<Double> getData(File file){
List<Double> listOfDoubles = new ArrayList<>();
try(Scanner scanner = new Scanner(file)){
while(scanner.hasNextDouble()) {
listOfDoubles.add(scanner.nextDouble());
}
}
return listOfDoubles;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
File inputFile = getFile();
return getData(inputFile);
}

Call the exact value from text File

Hi guys need help for my mini project for schools. How do i compare the user input and match to my database in text file. this is like validity for username and password. I want to call the second line on my data base using account Number and pin.
this is my data base.
0,admin,adminLastName,123456,123456
1,user,userLastName,1234567,123456
0 = id
admin = name
adminLastName = Last Name
1234567 = accountNumber
123456 = pin
and this is my code.
package atm;
import java.io.File;
import java.util.Scanner;
public class Login {
static void verifyLogin(String name, String lastName, String userAccountNumber, String userPin, String filePath){
Scanner inputData = new Scanner(System.in);
boolean isFound = false;
String tempAccountNumber = "";
String tempPin = "";
System.out.print("\nAccount Number: ");
userAccountNumber = inputData.next();
System.out.print("\nPIN: ");
userPin = inputData.next();
try{
Scanner readTextFile = new Scanner(new File("myDataBase.txt")).useDelimiter("[,\n]");
while (readTextFile.hasNext() && !isFound){
tempAccountNumber = readTextFile.next();
tempPin = readTextFile.next();
if (tempAccountNumber.trim().equals(userAccountNumber.trim()) && tempPin.trim().equals(userPin.trim())){
isFound = true;
System.out.println("Welcome " + name+ " " +lastName);
System.out.println("\nLogin Successfully!");
}
else {
System.out.println("You have entered your PIN or ACCOUNT NUMBER incorrectly. Please check your PIN or ACCOUNT NUMBER and try again.\n If you don't have account yet please go to SignUp page!\n");
myMain mainMenu = new myMain();
mainMenu.inputKeyboard();
}
}
readTextFile.close();
}
catch (Exception e){
}
inputData.close();
}
}
If your textfile contains 1 user per line, and you split it with ',' then you can take each line like you do, then split that line into a string[] array and check if i.e. the name corresponds to 'admin'.
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Boolean loggedin = false;
String fileName = "accounts.txt";
String line = null;
System.out.println("What's your username?");
String tempUsername = input.nextLine();
System.out.println("What's your password?");
String tempPassword = input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] currAccount = line.split(",");
if (currAccount[1].equals(tempUsername) && currAccount[4].equals(tempPassword)) {
loggedin = true;
System.out.println("You have successfully logged in!");
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
// Let's create it if file can't be found or doesn't exist, but let's ask first.
String answer;
System.out.print("File not found, do you want to create it? [Y/n]: ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y")) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("File has been created!");
} catch (IOException exc) {
exc.printStackTrace();
}
} else {
System.out.println("File was not created!");
}
}
catch(IOException ex) {
ex.printStackTrace();
}
if (!loggedin) {
System.out.println("Your login combination did not exist.");
}
}
}
Please note, I haven't commented a lot, but it should still make sense.
After splitting remember that you start at array index 0, and not 1. So at index 1 the name on the account will be.
Goodluck.

java keep trying until there are no more filenotfoundexception

I was trying to write code which would read an input file and create an output file. But when I tried to add a try until a correct input file name is input, I had problems. It shows not proper filenotfound exception is in try....
public static void main(String[] args) throws FileNotFoundException
{
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
finally
{
in.close();
out.close();
}
}
There is no method in your try block that may throw a FileNotFoundException.
Try to instantiate your Scanner in the try block. It will throw the expected FileNotFoundException if the filename read from stdin does not exist:
String inputfilename = null;
Scanner infile = null;
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
infile = new Scanner(new File(inputfilename));
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
Wrong here. You are only receiving input without checking if the file actually exist. Every valid inputs will let you get out of the loop.
if(new File(inputfilename).exist()){
done = true;
}else{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
You can only catch an exception if something in the try block may throw an exception.
However, you should test for existence of a file with File.exists(), instead of catching an exception.
File file;
do {
System.out.print("Input file name (from your computer): ");
file = new File(in.next());
} while (!file.exists());
Opening a file may throw an Exception. That's Why you need to put them inside try block. You have put only reading the input part inside try-catch block
Hope this code works properly:
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
finally
{
in.close();
out.close();
}

Writing more details in a file

actually am working on files and i have written exactly one person's details to a file ,now i want to write multiple person's details to that
file,i have tried using for loop but two files has been created and i want to write multiple person's details in the same file
import java.util.*;
import java.io.*;
public class Tourism {
String name;
String contact_number;
String address;
String enquiry_category;
String Des;
String price;
String location;
String packages;
Scanner s=new Scanner(System.in);
Scanner s1=new Scanner (System.in);
Scanner s2=new Scanner(System.in);
Scanner s3=new Scanner(System.in);
Scanner s4=new Scanner(System.in);
Scanner scan=new Scanner(System.in);
public void Choice(){
System.out.println("========menu========");
System.out.println("1.Initiate enquiry");
System.out.println("2.view enquiry");
System.out.println("3.exit");
System.out.println("enter the choice");
int ch;
ch=scan.nextInt();
switch(ch){
case 1:initiate();
break;
case 2:
View();
break;
case 3:
System.exit(0);
break;
}
}
public void initiate(){
for(int i=1;i<=2;i++){
System.out.println("=========="+i+"=========");
System.out.println("enter the name");
name=s.next();
System.out.println("enter the contact number");
contact_number=s1.nextLine()+"";
System.out.println("enter the address");
address=s2.nextLine()+"";
System.out.println(" enquiry categories:-");
System.out.println("enter the price range");
price=s1.nextLine()+"";
System.out.println("enter the location");
location=s2.nextLine()+"";
System.out.println("select/enter the package u want to have");
packages=s3.nextLine()+"";
System.out.println("enter the description of enquiry");
Des=s4.nextLine()+"";
}
try{
BufferedWriter br=new BufferedWriter(new FileWriter("Enquiry.txt"));
br.write(name);
br.newLine();
br.write("mobile number:"+contact_number);
br.newLine();
br.write("address:"+address);
br.newLine();
br.write("price:"+price);
br.newLine();
br.write("location:"+location);
br.newLine();
br.write("packages:"+packages);
br.newLine();
br.write("enquiry description:"+Des);
br.close();
}catch(IOException e){
System.out.println(e);
}
}
public void View(){
Scanner scanner=new Scanner(System.in);
System.out.println("enter the name to view the details");
String name1;
name1=scanner.nextLine();
try{
BufferedReader br=new BufferedReader(new FileReader("C:\\Users\\shashi.s\\Documents\\NetBeansProjects\\JavaApplication128\\Enquiry.txt"));
String line;
while((line=br.readLine())!=null){
if(line.equals(name1)){
System.out.println(line);
String line1;
while((line1=br.readLine())!=null){
System.out.println(line1);
}
}else{
System.out.println("oops "+name1+" .....does not exist");
break;
}
}
}catch(IOException e){
System.out.println(e);
}
}
public static void main(String[] args) {
Tourism t=new Tourism();
t.Choice();
}
}
use FileWriter(String fileName, boolean append)
instead of **new FileWriter("Enquiry.txt")**
the modified code tells to append text when boolean expression is true. but in your case it is only writing instead of appending next entered data.Hope you found my code helpful.
In your iteration you are just getting the values from console and storing to the variables,but not writing to the file.When you enter the second set of values it overwrites the first one.Finally, you come out of the loop and write the values to file.But the variables only hold the last entered values.
You can modify your code to write to the file,within the for loop itself,as modified below:
public void initiate() {
try {
BufferedWriter br = new BufferedWriter(new FileWriter("Enquiry.txt"));
for (int i = 1; i <= 2; i++) {
System.out.println("==========" + i + "=========");
System.out.println("enter the name");
name = s.next();
System.out.println("enter the contact number");
contact_number = s1.nextLine() + "";
System.out.println("enter the address");
address = s2.nextLine() + "";
System.out.println(" enquiry categories:-");
System.out.println("enter the price range");
price = s1.nextLine() + "";
System.out.println("enter the location");
location = s2.nextLine() + "";
System.out.println("select/enter the package u want to have");
packages = s3.nextLine() + "";
System.out.println("enter the description of enquiry");
Des = s4.nextLine() + "";
br.newLine();
br.write(name);
br.newLine();
br.write("mobile number:" + contact_number);
br.newLine();
br.write("address:" + address);
br.newLine();
br.write("price:" + price);
br.newLine();
br.write("location:" + location);
br.newLine();
br.write("packages:" + packages);
br.newLine();
br.write("enquiry description:" + Des);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}

Modify a specific content of a file with user defined value

This is my current output:
********MENU********
1. UNIT
2. EXIT
*********************
Select your option from 1 or 2: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1
This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify? 1
Asero/California
Asero/California
Unit Name: Iron Man
Unit Location: California
Return to menu? Select 1: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1
This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify?
Process interrupted by user.
What I wanted is the "Asero/California" is modified and replaced into "Iron Man/California".
The original output is still:
[1] Asero/California
[2] Captain America/Pennsylvania
My desired output is when I modify the data it should now be:
[1] Iron Man/California
[2] Captain America/Pennsylvania
I have a textfile = "practice.txt", which is where the data is stored.
I also have another text file = "tempPractice.txt", which is used just for putting a temporary data.
public class Practice
{
List<String> lines = new ArrayList<String>();
public Practice()
{
try
{
String line = "";
System.out.println("********MENU********");
System.out.println("1. UNIT");
System.out.println("2. EXIT");
System.out.println("*********************");
System.out.print("Select your option from 1 or 2: ");
Scanner sc = new Scanner(System.in);
line = sc.next();
if(line.equals("1"))
{
unitMenu();
}
else if(line.equals("2"))
{
System.exit(0);
}
else
{
System.out.println("Incorrect code, please select from 1 or 2.");
new Practice();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void unitMenu()
{
try
{
String line = "";
System.out.println("********MENU********");
System.out.println("1. VIEW LIST");
System.out.println("2. BACK TO MAIN");
System.out.println("*********************");
System.out.print("Select your option from 1 or 2: ");
Scanner sc = new Scanner(System.in);
line = sc.next();
if(line.equals("1"))
{
updateData();
}
else if(line.equals("2"))
{
new Practice();
}
else
{
System.out.println("Incorrect code, please select from 1 or 2.");
unitMenu();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void updateData()
{
lines = new ArrayList<String>();
File f = new File("practice.txt");
BufferedReader bR, bR2;
BufferedWriter bW;
Scanner sc, sc2;
String str = "", scanLine, oldFile, newFile, tmpFile, uName, uLoc;
int numLine;
try
{
if(!f.exists())
{
System.out.println("File not found!");
}
else
{
bR = new BufferedReader(new FileReader("practice.txt"));
while((str = bR.readLine()) != null)
{
lines.add(str);
}
System.out.println();
System.out.println("This are the list of the units:");
for(int i=0,j=1;i<lines.size();i++,j++)
{
System.out.println( "[" + j + "] " + lines.get(i).toString());
}
System.out.print("What unit do you want to modify? ");
sc = new Scanner(System.in);
numLine = sc.nextInt();
int count = numLine;
--count;
for(int k=0;k<lines.size();k++)
{
if(count == k)
{
System.out.println(lines.get(k).toString());
//used for checking to know what data it returns
oldFile = lines.get(count).toString();
System.out.println(oldFile);
//method to replace a data --> not working/trial and error?
bW = new BufferedWriter(new FileWriter("tmpPractice.txt"));
System.out.print("Unit Name: ");
sc = new Scanner(System.in);
uName = sc.nextLine();
bW.write(uName);
bW.append('/');
System.out.print("Unit Location: ");
sc2 = new Scanner(System.in);
uLoc = sc2.nextLine();
bW.write(uLoc);
bW.newLine();
bW.close();
System.out.print("Return to menu? Select 1: ");
sc = new Scanner(System.in);
scanLine = sc.next();
if(scanLine.equals("1"))
{
unitMenu();
}
else
{
System.out.println("Error. Select only 1.");
updateData();
}
bR2 = new BufferedReader(new FileReader("tmpPractice.txt"));
while((newFile = bR2.readLine()) != null)
{
tmpFile = newFile;
oldFile = tmpFile;
bW = new BufferedWriter(new FileWriter("practice.txt", true));
bW.write(oldFile);
bW.close();
}
System.out.println(oldFile);
bR2.close();
}
bR.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] a)
{
new Practice();
}
}
How would I do it? What should I do or what should I use in my code?
Is there any simplier way to do this? Any feedback/suggestion/remarks/help would be deeply much appreciated.
I'm still new to Java, and I'm doing a lot of practice for myself, I reached up to the point where I can append a data to a file with IO, however, I still dont know how to modify/replace a specific data in the file without deleting all of its contents.
Please help me, I really want to learn more.
Take a look at this and modify accordingly.
public static void replaceSelected(String address) {
try {
String x = "t";
System.out.println("started searching for line");
File inputFile1 = new File(old file where line is to be updated);
File tempFile = new File(address+"/myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(old file "));
String lineToRemove = "add line to remove as a variable or a text";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove) && x.contentEquals("t")) {
x ="f";
} else if(trimmedLine.equals(lineToRemove) && x.contentEquals("f")) {
System.out.println("removed desired header");
System.out.println("Line"+trimmedLine);
continue;
}
FileWriter fw = new FileWriter(new file address,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(currentLine);
System.out.println(currentLine);
bw.write("\n");
bw.close();
}
// writer.close();
reader.close();
boolean success3 = (new File (old file address)).delete();
if (success3) {
System.out.println(" Xtra File deleted");
}
} catch (Exception e){
}
I have worked out this code. In my code I have not used the temp file instead used the arraylist in to replace the old value with the new one.And After that I have write down the arraylist to the file. Please see below the changed code. I have only included the changed code here. This is working for me now.
for(int k=0;k<lines.size();k++)
{
if(count == k)
{
System.out.println(lines.get(k).toString());
//used for checking to know what data it returns
oldFile = lines.get(count).toString();
System.out.println(oldFile);
System.out.print("Unit Name: ");
sc = new Scanner(System.in);
uName = sc.nextLine();
System.out.print("Unit Location: ");
sc2 = new Scanner(System.in);
uLoc = sc2.nextLine();
String replaceString = uName+"/"+uLoc;
lines.set(k, replaceString);
FileOutputStream fop = null;
fop = new FileOutputStream(f);
for(String content:lines){
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.write("\n".getBytes());
}
fop.flush();
fop.close();
System.out.print("Return to menu? Select 1: ");
sc = new Scanner(System.in);
scanLine = sc.next();
if(scanLine.equals("1"))
{
unitMenu();
}
else
{
System.out.println("Error. Select only 1.");
updateData();
}
}
bR.close();
}
You used String replaceString = ...? Is the replaceString a value or a variable??
replaceString is a variable that contains the user enterd value to
replace the desired string value in the file
Another is this: lines.set(k, replaceString) -> can I also declare this as public void replaceString??? or is this the easier way?
here we are replacing the indexed(k) value in the arraylist(lines)
that contains the input file values, with the user enterd value.
And also, may I ask, what is the use of byte[], is it like charAt[] or more like Tokenizer?
now the replaced content is writing back to the file. For this we are
converting the string value to the byte array(byte []) and writing
using the FileOutputStream

Categories