Cant delete original file and rename temp file - java

Im trying to delete the original file ("order2.txt") and rename the temp file to ("order2.txt") that I have store the new data. But for some reason the original could not be delete and it also cant rename the temp file. Anyone know what is wrong with my code and how can i fix it??
void editRecord(String editTerm){
String tempFile="temp.txt";
String file="order2.txt";
File oldFile=new File(file);
File newFile=new File(tempFile);
String ID1="";
String status1="";
String food1="";
String fq1="";
String d1="";
String dq1="";
System.out.println("l");
try{
System.out.println("2");
FileWriter fw=new FileWriter(tempFile,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
Scanner x=new Scanner(new File(file));
x.useDelimiter("[,\n]");
System.out.println("3");
while(x.hasNext()){
ID1=x.next();
status1=x.next();
food1=x.next();
fq1=x.next();
d1=x.next();
dq1=x.next();
System.out.println(dq1);
String newStatus =statusTextField.getText();
if(ID1.equals(editTerm))
{
System.out.println(status1);
pw.println(ID1+","+newStatus+","+food1+","+fq1+","+d1+","+dq1);
System.out.println(ID1+","+newStatus+","+food1+","+fq1+","+d1+","+dq1);
}
else
{
System.out.println(ID1+","+status1+","+food1+","+fq1+","+d1+","+dq1);
pw.println(ID1+","+status1+","+food1+","+fq1+","+d1+","+dq1);
System.out.println("y");
}
System.out.println("t");
}
x.close();
pw.flush();
pw.close();
System.out.println("t");
oldFile.delete();
File dump = new File(file);
newFile.renameTo(dump);
System.out.println("f");
}
catch(IOException ex) {
System.out.println("fail");
}
}

Related

Deleting a record in a file in Java

public class Client {
private Scanner scanner;
private String fileClient="client.txt";
public File client =new File(fileClient);
public void deletClient() {
int lineRemove =GetLineRemove();
String tempFile="temp.txt";
File newfile=new File(tempFile);
int line=0;
String currentLine;
try {
FileWriter fw=new FileWriter(tempFile,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
FileReader fr=new FileReader(fileClient);
BufferedReader br=new BufferedReader(fr);
while((currentLine=br.readLine())!=null ) {
line++;
if(line !=lineRemove) {
pw.println(currentLine);
}
}
pw.flush();
fr.close();
bw.close();
pw.close();
br.close();
fw.close();
// i try to delet a file
client.delete();
// create a file have the same name
File dumy=new File(fileClient);
// rename it to first file
newfile.renameTo(dumy);
}catch(Exception e){
System.out.print(e);
}
}
I want to remove a line from a file but when i do that i found the first file still exist and the second file what should get rename to the first file still have has it name temp i don't know should do so i hope u can help me to know where is the problem.

Java functions delete() and renameTo() not deleting nor renaming

public void newEditSportRecord(){
String filepath = "sport.txt"; //exists in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
String editTerm = JOptionPane.showInputDialog("Enter ID of Sport you wish to modify:");
String tempFile = "temp.txt"; // to be created in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
File oldFile = new File(filepath);
System.out.println(oldFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\sport.txt
File newFile = new File(tempFile);
System.out.println(newFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\temp.txt
String ID, name = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
while (x.hasNextLine()) {
ID = x.next();
System.out.println(ID);
name = x.next();
System.out.println(name);
if (ID.equals(editTerm)) {
newID = JOptionPane.showInputDialog("Enter new Sport ID:");
newName = JOptionPane.showInputDialog("Enter new Sport Name:");
pw.println(newID);
pw.println(newName);
pw.println();
JOptionPane.showMessageDialog(modifySport, "Record Modified");
} else {
pw.println(ID);
pw.println(name);
pw.println();
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception ex) {
JOptionPane.showMessageDialog(modifySport, ex);
}
}
I have the following function to try and modify a text file. However, it does NOT delete the original file "sport.txt" nor does it rename "temp.txt" to "sport.txt". It DOES read from the file and create a copy of "sport.txt" with all the relevant modifications as "temp.txt". I had suspected it was a problem with the writers but having closed all of them, the issue still persists. Is this simply down to permission problems as the folder exists in the Documents folder on Local Disk?
Yes, it is a permission problem. Either change the permission of the Documents folder and give access to all the permissions to your user or change your working folder.

Java not deleting text file

When I test the program within the class, it deletes temp.txt fine, but when I call it from another class, it fails to delete. Any help much appreciated! (ps- I haven't attached the class from which I'm calling it)
public class txtWriteReadDelete{
public static void deleteRecord(String filePath,String usernameDelete) {
String tempFile="temp.txt";
File oldFile=new File(filePath);
System.out.println("oldFile: "+ oldFile);
File newFile=new File(tempFile);
String username="";String password="";
try {
FileWriter fileWriter=new FileWriter(tempFile,true);
BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);
PrintWriter printWriter=new PrintWriter(bufferedWriter);
Scanner x=new Scanner(new File(filePath));
x.useDelimiter("[,\n]");
while (x.hasNext()){
username=x.next();
password=x.next();
if(!username.equals(usernameDelete)) {
System.out.println(username);
printWriter.println(username + "," + password);
}
x.close();
printWriter.flush();
printWriter.close();
boolean deleted = oldFile.delete();
System.out.println("temp deleted: "+deleted);
File dump=new File(filePath);
newFile.renameTo(dump);
}
catch(Exception E) {
E.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR");
}
Deleting a file using .delete() operation expect a valid path. If the path is incorrect .delete() would not be able to delete the file.
You can check the validity of the file using oldFile.isFile() operation.
You need to provide the complete path of the file.

How to capture the file name from the server dynamically when some one uploads it

Below is the code to read the file from the server. I Want to read & convert the file dynamically (not hard coded )into different file format(CSV). Could anyone please guide me to capture the uploaded file name dynamically.
try
{
//creating File instance to reference text file in Java
String str1=null;
String str2=null;
String str3=null;
int cnt=0,len1=0,len2=0;
File text = new File("C:\\Petty Ascii Detail.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
File file = new File("C:\\Test\\Write1.txt");
//if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine())
{
String line = scnr.nextLine();
cnt=line.length();
for(int i=0;i<3;i++)
{
if (Character.isDigit(line.charAt(i)))
str1=line;
else
str2=line;
}
len1=str1.length();
len2=str2.length();
if(len1!=len2)
{
str3=str1+str2;
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str3);
bw.newLine();
System.out.println("Done");
bw.close();
}
lineNumber++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions are really appreciated.
Thanks,
Balaji

Java appending new file's data to old file

In the first step am creating a file say test1.txt and adding records to it, and the rest records to test2.txt. Now i want to append the records of test2.txt to test1.txt. How to append them to test1.txt. The reason am dividing the files is i have a List with about 53K records, which am unable to write in a single file, as the buffer writer is closing as its reaching 52K.
The function am using for creating a single file is
public void exportApprovedList() throws IOException {
File approvedWhiteListFile = new File("/var/tmp/livecron/dictionary.common");
BufferedWriter bw = new BufferedWriter(new FileWriter(approvedWhiteListFile));
if (approvedWhiteListFile.exists()) {
List<WhiteListTerm> approvedWhiteList = whiteListBO.getByStatus("APPROVED");
for (WhiteListTerm whiteList : approvedWhiteList) {
bw.write(whiteList.getTerm() + "|" +
whiteListCategoryBO.getById(whiteList.getCategoryId()).getCategoryname());
bw.newLine();
}
}
bw.close();
}
try this....
import java.io.*;
public class FileReadWrite {
public void writeFile(String sorcefile)
{
try{
FileInputStream fis = new FileInputStream(sorcefile);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
FileWriter fw=new FileWriter("src/output.java",true);
BufferedWriter bw=new BufferedWriter(fw);
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
System.out.println (strLine);
bw.append(strLine);
}
//Close the input stream
br.close();
dis.close();
fis.close();
fw.flush();
bw.flush();
fw.close();
bw.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String args[])
{
FileReadWrite frw=new FileReadWrite();
frw.writeFile("sorce file name wit hfull path");
}
}

Categories

Resources