I cannot delete a .dat file using file operations of Java [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I have tried a number of methods for deleting a .dat file using the file operations of Java but none seem to work for me. The methods that I have tried are all searched from StackOverflow. Below is my code:
public static void removeRecords(Scanner in, ArrayList<BankAccount> listOfAccounts) throws IOException {
System.out.println("Enter Administrator Password:");
String password = in.next();
if (password.equals("2022")) {
// The file pathname should be edited according to the directory where the program files are placed
File folder = new File("C:/Users/nilay/OneDrive/Desktop/Bank Account/");
File fList [] = folder.listFiles();
// Searching for accountList.dat and deleting the file
boolean success = false;
for (File file: fList) {
if (file.getName().endsWith(" .dat")) {
success = file.delete();
}
}
if (success) {
System.out.println("All account records have been successfully removed. Returning back to Main Menu.");
} else if (!success) {
System.out.println("File not deleted.");
}
}
I always get "File not deleted" as the output. Please help me.

File.delete() will return true only if it deletes the file. Meaning it will return false if the file does not exist. Ensure File.exists() returns true prior to invoking File.delete():
if (file.exists()) {
if (file.delete()) {
} else {
}
}
Also see Files.deleteIfExists() which may provide more information, via an IOException, in the event of a failed deletion attempt:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
try {
final Path p = Paths.get(searchCust + " booking.dat");
if (Files.deleteIfExists(p)) {
JOptionPane.showMessageDialog(null, "Deleted " + p);
} else {
JOptionPane.showMessageDialog(null, p + " does not exist.");
}
}
catch (final IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}

Related

How to write a program that reads from and write to file

I'm reading a file with numbers checking if the number is a prime number then writing next to the prime numbers "is a prime" and printing that out to a different file,
I keep getting:
Failed to open file in4.txt Exiting...
This is my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class CheckPrimes {
public static void checkPrimes(String in_file, String out_file) {
File temp = new File(in_file);
Scanner input;
try
{
input = new Scanner(temp);
}
catch (Exception e)
{
System.out.printf("Failed to open file %s\n", in_file);
return;
}
while (true)
{
for (int i = 2; i < input.nextInt(); i++)
{
if (input.nextInt() % i != 0)
{
try{
PrintWriter output = new PrintWriter(out_file);
output.print( input.nextInt() + " is prime");
output.close();
}
catch(IOException ex)
{
System.out.printf("Error : %s\n",ex);
}
}
}
}
{
public static void main(String[] args)
{
checkPrimes("in4.txt", "out4.txt");
System.out.printf("Exiting...\n");
}
}
Longshot but might work since someone had that problem on this site yesterday. I referred them to this answer on a different topic where the File URL is formatted differently into a path that java seems to accept better that plaintext filepaths.
For the error you are receiving (Failed to open file in4.txt), just make sure that the file you are reading is on the same file level as your JAR (or file if running in an IDE). Alternatively, you can run the createNewFile() function and edit the created function.
(IntelliJ runs the file from the base of the project, hence why my files aren't where the class file is).
However, upon running the code myself, I was receiving this error: java.util.NoSuchElementException. I was able to correct this by switching from readInt() to readLine(), and having the in4.txt file structured as shown:
1
3
5
7
9
I believe readInt() not working versus readLine() is due to the problem presented in this problem. Also, be wary of calling readLine/readInt multiple times rather than assigning a variable per loop iteration because every call progresses the scanner (more info here).

Generating text file named as a user's name in java console based app [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
how to generate text file named as a user's name while generating receipt for him/her when he purchases a book,in java console based application.Help me out.
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
public class BookApplication {
public static void main(String[] args) {
try {
System.out.println("Hi , Enter Your Name ?");
Scanner scanner =new Scanner(System.in);
String username= scanner.nextLine();
String MY_OUTPUT_PATH="";//your path where you want your file
boolean bookPurchased=true; // Do your code for bookpurchase
if(bookPurchased){
File receipt= new File(MY_OUTPUT_PATH+ File.separator+username+".txt");
FileOutputStream outputStream =new FileOutputStream(receipt);
String sampleData=username+" has purchased a book for rs.500";
outputStream.write(sampleData.getBytes());
outputStream.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
This is what I can give you from your Question. Try working on what you want, then ask Questions.

Run program with file in java [duplicate]

This question already has answers here:
FileNotFoundException error while running java program
(5 answers)
Closed 8 years ago.
Okay so I'm doing homework for my AI class and the code I list below was given. All I need to do is modify it slightly but that's aside the point, I can do that. What I need help with is I was told I have to run the program with input from a file like this: ReflexRover < < filename >
When I run the program I can give it individual numbers that the default constructor accepts and everything is fine. But When I give it a file name it says failed to open. I don't know how to use eclipse that well so is there a special way I'm supposed to run the program to send it the file?
Note: there is no problem with the code itself
import java.io.*;
import java.lang.*;
/**
* RovingSampleSensors: A class for reading sample perceptions from a file
* and presenting them one at a time
*
* #author
* #version 1.1
*
* allowed stdin version of contstructor
*/
public class RoverSampleSensor {
// File
private BufferedReader myFile;
/**
* Creates Sensors object from file
* #param filename The file that data is read from
*/
public RoverSampleSensor(String filename) {
try {
myFile=new BufferedReader(new FileReader(filename));
} catch (Exception e) {
System.err.println("Ooops! I can't seem to load the file \""+filename+"\", do you have the file in the correct place?");
System.exit(1);
}
}
/**
* Creates Sensors object from standard input
*/
public RoverSampleSensor() {
try {
myFile=new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
System.err.println("Ooops! I can't seem to read from the standard input!");
System.exit(1);
}
}
/**
* Gets the next sample perception
* #return SamplePercept A SamplePercept object containing the percept
*/
public SamplePercept getPercept() {
String line;
try {
line=myFile.readLine();
if (myFile==null) {
return null;
} else if (line==null) {
try {
myFile.close();
} catch (Exception e) {
}
myFile=null;
return null;
} else {
return new SamplePercept(line);
}
} catch (Exception e) {
System.err.println("Ooops! I seem to have gotten an i/o error reading the file.");
System.exit(1);
}
return null;
}
/**
* Run a test of the reading routines, prints out all percepts of the file
*
* Usage: java RoverSampleSensor -file <filename>
*/
public static void main(String args[]) {
if (args.length!= 0 &&
(args.length != 2 || (! args[0].equals("-file")))) {
System.err.println("Usage: RoverSampleSensor -file <filename>");
System.exit(1);
}
RoverSampleSensor rss=null;
SamplePercept sp;
if (args.length==0) {
rss=new RoverSampleSensor();
} else {
rss=new RoverSampleSensor(args[1]);
}
while((sp=rss.getPercept())!=null) {
System.out.println("Percept: "+sp.value());
}
}
}
Okay allow me to refine my question. This is what I did: I click run, the console pops up, I can enter integers one by one no problem. I just need to know how to get the program to work when I do RoverSampleSensor . The file is already at the same level as my src. Every time I try it catches my exception and says ""Ooops! I seem to have gotten an i/o error reading the file". I cant print the stack trace because I'm not supposed to change that part of the code. Am I not supposed to hit run before I try to send it the file? Is there a different way I am supposed to run it?
If you are working under Eclipse and don't intend to export your project in a jar file, an easy solution is to put your file at the root of the project (at the same level of the folder src). If you do that, the path to the file will only consist in its name.
If you launch your program with a console command, you must provide the path to the file accordingly to the current folder in the console.

How to delete .dat file in Java?

I want to delete a .dat file. This is my code but it does not work.
String searchCust = SearchCust.getText();
File file = new File(searchCust + " booking.dat");
if (file.delete()) {
JOptionPane.showMessageDialog(null, "Info deleted");
} else {
JOptionPane.showMessageDialog(null, "Delete failed");
}
Basically when i run, the file is not deleted and the "Delete failed" message will appear
File.delete() will return true only if it deletes the file. Meaning it will return false if the file does not exist. Ensure File.exists() returns true prior to invoking File.delete():
if (file.exists())
{
if (file.delete())
{
}
else
{
}
}
Also see Files.deleteIfExists() which may provide more information, via an IOException, in the event of a failed deletion attempt:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
try
{
final Path p = Paths.get(searchCust + " booking.dat");
if (Files.deleteIfExists(p))
{
JOptionPane.showMessageDialog(null, "Deleted " + p);
}
else
{
JOptionPane.showMessageDialog(null, p + " does not exist.");
}
}
catch (final IOException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
if(file.exists()){
boolean isDelete = file.delete();
if(isDelete){
//condition
}else{
//condition
}
}
Code looks good
fileObject.delete() is the way to delete the record. But you should know what is the current working directory in java first.
Try the below command. Check for its availability : fileObject.exists()
System.getProperty("user.dir"); // fetches the current working directory.
This is the approach, you can fix this problem.

Java: how to synchronize file modification by threads

Only one instance of my Java application can run at a time. It runs on Linux. I need to ensure that one thread doesn't modify the file while the other thread is using it.
I don't know which file locking or synchronization method to use. I have never done file locking in Java and I don't have much Java or programming experience.
I looked into java NIO and I read that "File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine." Right away I knew that I needed expert help because this is production code and I have almost no idea what I'm doing (and I have to get it done today).
Here's a brief outline of my code to upload some stuff (archive files) to a server. It gets the list of files to upload from a file (call it "listFile") -- and listFile can be modified while this method is reading from it. I minimize the chances of that by copying listFile to a temp file and using that temp file thereafter. But I think I need to lock the file during this copy process (or something like that).
package myPackage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import com.example.my.FileHelper;
import com.example.my.Logger;
public class BatchUploader implements Runnable {
private int processUploads() {
File myFileToUpload;
File copyOfListFile = null;
try {
copyOfListFile = new File("/path/to/temp/workfile");
File origFile = new File("/path/to/listFile"); //"listFile" - the file that contains a list of files to upload
DataWriter.copyFile(origFile, copyOfListFile);//see code below
} catch (IOException ex) {
Logger.log(ex);
}
try {
BufferedReader input = new BufferedReader(new FileReader(copyOfListFile));
try {
while (!stopRunning && (fileToUploadName = input.readLine()) != null) {
upload(new File(fileToUploadName));
}
} finally {
input.close();
isUploading = false;
}
}
return filesUploadedCount;
}
}
Here is the code that modifies the list of files to be uploaded used in the above code:
public class DataWriter {
public void modifyListOfFilesToUpload(String uploadedFilename) {
StringBuilder content = new StringBuilder();
try {
File listOfFiles = new File("/path/to/listFile"); //file that contains a list of files to upload
if (!listOfFiles.exists()) {
//some code
}
BufferedReader input = new BufferedReader(new FileReader(listOfFiles));
try {
String line = "";
while ((line = input.readLine()) != null) {
if (!line.isEmpty() && line.endsWith(FILE_EXTENSION)) {
if (!line.contains(uploadedFilename)) {
content.append(String.format("%1$s%n", line));
} else {
//some code
}
} else {
//some code
}
}
} finally {
input.close();
}
this.write("/path/to/", "listFile", content.toString(), false, false, false);
} catch (IOException ex) {
Logger.debug("Error reading/writing uploads logfile: " + ex.getMessage());
}
}
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
}
private void write(String path, String fileName, String data, boolean append, boolean addNewLine, boolean doLog) {
try {
File file = FileHelper.getFile(fileName, path);
BufferedWriter bw = new BufferedWriter(new FileWriter(file, append));
bw.write(data);
if (addNewLine) {
bw.newLine();
}
bw.flush();
bw.close();
if (doLog) {
Logger.debug(String.format("Wrote %1$s%2$s", path, fileName));
}
} catch (java.lang.Exception ex) {
Logger.log(ex);
}
}
}
My I suggest a slightly different approach. Afair on Linux the file rename (mv) operation is atomic on local disks. No chance for one process to see a 'half written' file.
Let XXX be a sequence number with three (or more) digits. You could let your DataWriter append to a file called listFile-XXX.prepare and write a fixed number N of filenames into it. When N names are written, close the file and rename it (atomic, see above) to listFile-XXX. With the next filename, start writing to listFile-YYY where YYY=XXX+1.
Your BatchUploader may at any time check whether it finds files matching the pattern listFile-XXX, open them, read them upload the named files, close and delete them. There is no chance for the threads to mess up each other's file.
Implementation hints:
Make sure to use a polling mechanism in BatchUploader that waits 1 or more seconds if it does not find a file ready for upload (prevent idle wait).
You may want to make sure to sort the listFile-XXX according to XXX to make sure the uploading is kept in sequence.
Of course you could variate the protocol of when listFile-XXX.prepare is closed. If DataWriter has nothing to do for a longer time, you don't want to have files ready for upload hang around just because there are not yet N ready.
Benefits: no locking (which will be a pain to get right), no copying, easy overview over the work queue and it state in the file system.
Here is a slightly different suggestion. Assuming your file names don't have '\n' characters in them (it's a big assumption on linux, I know, but you can have your writer look up for that), why not only read complete lines and ignore the incomplete ones? By incomplete lines, I mean lines that end with EOF and not with \n.
Edit: see more suggestions in comments below.

Categories