Writing more details in a file - java

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

Related

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 Reading the file and displaying users search

I am new to java and i'm trying to fetch the contents of the file and the type contents are
Nameofuser:DateOfBirth:Nationality
I want to ask users which name to find and the name should search the first field and again ask for dob and get results so on.
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.next());
input = new Scanner(file);
String newInput = input.nextLine();
while (input.hasNext()) {
String line = input.next();
String delims = "[:]";
String[] tokens = line.split(delims);
System.out.println(tokens);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("Error Occured ");
}
}
}
How do i go about displaying the search.
you need to get target name and dob, then try to find that record in the while loop
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
String dob="",name="";
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.next());
//get person name and dob to search for:
System.out.print("Enter Person name : ");
name = input.next();
System.out.print("Enter Person DOB : ");
dob = input.next();
input = new Scanner(file);
String newInput = input.nextLine();
boolean found = false;
while (input.hasNext()) {
String line = input.next();
String delims = "[:]";
String[] tokens = line.split(delims);
//check if this line matches target record
if(tokens[0].equals(name) && tokens[1].equals(dob)){
System.out.println(String.format("Found Record, name: %s DOB: %s Nationality: %s",tokens[0],tokens[1],tokens[2]));
found=true;//mark as a record found
//no need to loop further
break;
}
}//while loop
if(!found){
System.out.println("No match records found!");
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("Error Occured ");
}
}
}

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

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

Error Array index out of bound when i m add the object in array list

**Here is my code when i m adding the object in array list error display Exception in thread "main" `
**java.lang.ArrayIndexOutOfBoundsException :1**`
`**at Customer.withDrawal(Customer.java:47**`)
**at Customer.displayMenu(Customer.java:19)**
**at AtmTest.main(AtmTest.java:6)**
when is occur i don't know what is the problem but please help me bcz its my software of atm machine due to this error i cannot do work of next function.**
import java.util.*;
import java.io.*;
public class Customer{
static String cavailablebal;
Scanner reader=new Scanner(System.in);
ArrayList witharraylist=new ArrayList();
public void displayMenu()
{
System.out.println ("1----Withdraw Cash");
System.out.println ("2----Cash Transfer");
System.out.println ("3----Deposit Cash");
System.out.println ("4----Display Balance");
System.out.println ("5----Exit ");
System.out.println("Enter your choice");
char choice1=reader.next().charAt(0);
switch(choice1)
{
case'1':
withDrawal();
break;
}
}//end displayMenu
public void withDrawal()
{
String id,accountid,name,type,pamount,status;
String actualbal;
char choice1,choice2,confirm;
int withdrawalbal,availablebal;
int cactualbal;
Login obj2=new Login();
try
{
FileReader fr=new FileReader("account.txt");
BufferedReader br=new BufferedReader(fr);
String fileread=br.readLine();
System.out.println(fileread);
String tokens[];
while (fileread!=null)
{
tokens=fileread.split(",");
id=tokens[0];
accountid=tokens[1];
name=tokens[2];
type=tokens[3];
pamount=tokens[4];
status=tokens[5];
fileread=br.readLine();
LoginInfo lo=new LoginInfo(id,accountid,name,type,pamount,status);
witharraylist.add(lo);
}
System.out.println("1----Fast Cash");
System.out.println("2----Normal Cash");
System.out.println("3----Exit");
System.out.println("Enter your Choice:");
choice1 = reader.next().charAt(0);
switch(choice1)
{
case'1':
System.out.println("1----500");
System.out.println("2----1000");
System.out.println("3----2000");
System.out.println("4----5000");
System.out.println("5----10000");
System.out.println("6----15000");
System.out.println("7----20000 ");
System.out.println("Select one of the denominations of money:");
choice2 = reader.next().charAt(0);
if(choice2=='1')
{
System.out.println("Are you sure you want to withdraw Rs.500 (Y/N)?");
confirm = reader.next().charAt(0);
if (confirm=='y'||confirm=='Y')
{
String get=obj2.setid;
for(int i=0;i<witharraylist.size();i++)
{
LoginInfo low=(LoginInfo)witharraylist.get(i);
if(get.equals(low.pid))
{
withdrawalbal=500;
actualbal=low.amount;
cactualbal=Integer.parseInt(actualbal);
availablebal=cactualbal-withdrawalbal;
cavailablebal=Integer.toString(availablebal);
System.out.println("Your Available balance:"+cavailablebal);
witharraylist.set(i,low);
writeValues();
}
}
}
else
{
System.out.println("Transfer not successfully");
withDrawal();
}
}
break;
}
}catch(IOException ex)
{
System.out.println(ex);
}
}
public void writeValues()
{
try{
String line;
FileWriter fw=new FileWriter("account.txt");
PrintWriter pw=new PrintWriter(fw);
for(int i=0;i<witharraylist.size();i++){
LoginInfo wr=(LoginInfo)witharraylist.get(i);
line=wr.pid+","+wr.accountid+","+wr.name+","+wr.type+","+wr.amount+","+wr.status;
pw.println(line);``
}
pw.flush();
fw.close();
pw.close();![this is the image of error][1]
}catch(IOException ex)
{
System.out.println(ex);
}
}
}
<code>
How about
while (fileread!=null)
{
tokens=fileread.split(",");
if (tokens.length >= 6) {
id=tokens[0];
accountid=tokens[1];
name=tokens[2];
type=tokens[3];
pamount=tokens[4];
status=tokens[5];
LoginInfo lo=new LoginInfo(id,accountid,name,type,pamount,status);
witharraylist.add(lo);
}
else {
System.out.println ("Oh dear!!");
}
fileread=br.readLine();
}
there may be a problem with the text file account.txt like less number of commas(,). Please check them because you are using the split function.

How to delete a line from a data file or text file?

I have a program that calls for the data file to have sections that displays all employees, individual employees, insert an employee, and delete an employee.
Below is the full code but I have no clue how to do the delete portion
import java.io.*;
import java.util.*;
import java.util.Scanner;
import javax.swing.*;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Program6pt2
{
static Scanner scan = new Scanner (System.in);
static String str, FName, LName, SS, SS1, Name;
static double pay, hours;
static double rate, gross, overtime, net, NO, fed, state, deduction;
static double union=7.85, hospital=25.65;
static char ch, ch1;
static int num, i;
//static Scanner scan= new Scanner(System.in);
public static void main(String[] args)throws FileNotFoundException, IOException
{
Scanner infile= new Scanner(new FileReader("G:\\Program5.txt"));
{
System.out.println("########################################################");
System.out.println("# The purpose of the following algorithms #");
System.out.println("# are to find the area, surface area, volume,` #");
System.out.println("# and compound interest of the following programs #");
System.out.println("########################################################");
do {
System.out.println("######################################################");
System.out.println("# #");
System.out.println("# MENU #");
System.out.println("# 1. Individual Employees #");
System.out.println("# 2. All Employees #");
System.out.println("# 2. Insert #");
System.out.println("# 2. Quit #");
System.out.println("######################################################");
System.out.println();
System.out.println(" Please enter 1 or 2 to quit ");
num = scan.nextInt();
switch (num)
{
case 1:individual(SS, LName, FName, pay, hours);
break;
case 2: all(SS, LName, FName, pay, hours);
break;
case 3: insert(SS, LName, FName, pay, hours);
break;
case 4: delete(SS, LName, FName, pay, hours);
break;
default: System.out.println("Thank you so much for using this Program!");
}
}while(num != 5);
}
}
public static void individual(String a, String b, String c, double d, double e)throws FileNotFoundException, IOException
{
Scanner infile= new Scanner(new FileReader("G:\\Program5.txt"));
int i=0;
System.out.println("---****************************************************************---");
System.out.println("--- THIS MENU ALLOWS THE USER TO SELECT A SS NUMBER OR AN ****---");
System.out.println("--- INDIVIDUAL'S NAME AND DISPLAY ALL THEIR INFO AS WELL ****---");
System.out.println("--- DISPLAY ALL THE NAMES IN THE LIST AS WELL AS THEIR SS # IN ***----");
System.out.println("--- A LIST ****---");
System.out.println("---****************************************************************---");
do
{
System.out.println("################### #########################");
System.out.println("# MAIN MENU #");
System.out.println("# 1. Enter The Social Security Number #");
System.out.println("# 2. Quit #");
System.out.println("# 3. Main Menu #");
System.out.println("# #");
System.out.println("#############################################");
System.out.println();
System.out.println(" Please enter 1,2,3 or 4 ");
num = scan.nextInt();
System.out.println();
switch (num)
{
case 1:SSnumber(a,b,c,d,e);
break;
case 3: System.out.println("Please enter a number");
break;
default: System.out.println("Please select A, B, C, or D to Quit");
break;
}
}while(num != 3);
}
public static void SSnumber(String A, String B, String C, double D, double E)throws FileNotFoundException, IOException
{
Scanner infile = new Scanner(new FileReader("G:\\Program5.txt"));
int i=0;
System.out.print("Enter the employee number (ex. 111-11-1111) : ");
SS1= scan.next();
System.out.println();
System.out.println("-----------------------------------------------------------------------------------------------------------");
System.out.printf("%-4s%10s%13s%8s%10s%14s%12s%13s%10s%n", "NO.", "Last Name", "First Name", "Hours", "Payrate", "Overtime Pay", "Gross Pay", "Deductions", "Net Pay");
System.out.println("-----------------------------------------------------------------------------------------------------------");
while (infile.hasNext())
{
A= infile.next();
B= infile.next();
C= infile.next();
D= infile.nextDouble();
E= infile.nextDouble();
++i;
if(A.compareTo(SS1) ==0)
{
if(E>40)
{
overtime= 1.5*D*(E-40);
gross= overtime+ (D*40);
}
else
{
overtime=0;
gross= E*D;
}
fed=gross*0.18;
state=gross*0.045;
deduction=fed+state+hospital+union;
net=gross-deduction;
//System.out.println(+i+ B+ C+ E+ D+ overtime+ gross+ deduction+ net);
System.out.printf("%-5d%-12s%-12s%6.1f%9.2f%10.2f%15.2f%13.2f%10.2f%n", i, B, C, E, D, overtime, gross, deduction, net);
}
}
infile.close();
System.out.println();
System.out.println();
}
public static void all(String a, String b, String c, double d, double e)throws FileNotFoundException, IOException
{
Scanner infile = new Scanner(new FileReader("G:\\Program5.txt"));
int i=0;
System.out.println("-----------------------------------------------------------------------------------------------------------");
System.out.printf("%-4s%10s%13s%8s%10s%14s%12s%13s%10s%n", "NO.", "Last Name", "First Name", "Hours", "Payrate", "Overtime Pay", "Gross Pay", "Deductions", "Net Pay");
System.out.println("-----------------------------------------------------------------------------------------------------------");
while (infile.hasNext())
{
a= infile.next();
b= infile.next();
c= infile.next();
d= infile.nextDouble();
e= infile.nextDouble();
++i;
if(e>40)
{
overtime=1.5*d*(e-40);
gross= overtime+(d*40);
}
else
{
overtime=0;
gross=e*d;
}
fed=gross*0.18;
state=gross*0.045;
deduction=fed+state+union+hospital;
net=gross-deduction;
System.out.printf("%-5d%-12s%-12s%6.1f%9.2f%10.2f%15.2f%13.2f%10.2f%n", i, b, c, e, d, overtime, gross, deduction, net );
}
infile.close();
System.out.println();
System.out.println();
}
public static void insert(String a, String b, String c, double d, double e)throws FileNotFoundException
{
Scanner infile = new Scanner(new FileReader("G:\\Program5.txt"));
try
{
while (infile.hasNext())
{
a= infile.next();
b= infile.next();
c= infile.next();
d= infile.nextDouble();
e= infile.nextDouble();
}
System.out.print("Enter the ID number (ex.111-22-3333) : ");
a=scan.next();
System.out.print("Enter the Last Name (ex. Smith) : ");
b=scan.next();
System.out.print("Enter the First Name (ex. John) : ");
c=scan.next();
System.out.print("Enter the pay rate (ex 7.00) : ");
d=scan.nextDouble();
System.out.print("Enter the hours worked (ex 57.0) : ");
e=scan.nextDouble();
FileWriter insert1 = new FileWriter("G:\\Program5.txt", true);
insert1.append("\n");
insert1.append(a + " ");
insert1.append(b + " ");
insert1.append(c + " ");
insert1.append(d + " ");
insert1.append(e + "\n");
insert1.close();
}
catch(Exception o)
{
System.out.println("Wrong");
}
System.out.println();
}
public static void delete(String a, String b, String c, double d, double e)throws FileNotFoundException
{
Scanner infile = new Scanner(new FileReader("G:\\Program5.txt"));
try
{
boolean append=false;
Scanner inFile = new Scanner(new FileReader("G:\\Program5.txt"));
FileWriter outfile= new FileWriter("G:\\Program5.txt", append);
BufferedWriter print = new BufferedWriter(outfile);
System.out.println("choose a employee to delete from the system.");
System.out.print("Enter the employee Social Security Number: ");
SS= scan.next();
{
print.write("\n");
print.write( a + " " );
print.write( "\n");
}
print.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("Wrong");
}
System.out.println();
}
}
See Answer provided here: Java - delete line from text file by overwriting while reading it.
Your best bet is to write the modified version of the file (with the part that you want to delete removed) to a temporary file, delete (or backup) original file, and then rename to the original file name.
You can use the code below to replace the wanted line with "" or null;
public static boolean readReplace(String fileName, String oldPattern,
String replPattern, int lineNumber) {
String line;
StringBuffer sb = new StringBuffer();
int nbLinesRead = 0;
try {
FileInputStream fis = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(
fis));
while ((line = reader.readLine()) != null) {
nbLinesRead++;
line = line.toLowerCase();
if (nbLinesRead == lineNumber) {
line = line.replaceFirst(oldPattern.toLowerCase(),
replPattern);
}
sb.append(line + "\n");
}
reader.close();
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write(sb.toString());
out.close();
} catch (Exception e) {
return false;
}
return true;
}
Short answer: You can't.
Long answer: Create a new file and copy all lines except the one you don't one to that file. After that, rename the old file, then the new file and maybe remove the old one.

Categories