Java: How to delete a file - java

In the code below how come when it say that it has successfully deleted the file, but when I check the file is still there. How would I remove the file. Basically I'm trying the delete the first file that I made after I was done using it to create the second file.
public static void main(String[] args) {
File file = new File("Hello");
try {
file.createNewFile();
} catch (Exception e) { }
try {
PrintWriter e = new PrintWriter(file);
e.println("Hello hi");
e.close();
}catch (Exception e) {}
File file2 = new File("Hello2");
try {
file2.createNewFile();
} catch (Exception e) {}
try {
Scanner x = new Scanner(file);
PrintWriter e = new PrintWriter(file);
while (x.hasNextLine()) {
System.out.println("Hello");}
e.close();
} catch (Exception e) {}
try {
file.delete();
System.out.println("It was deleted");
} catch (Exception e) { }
}
}

file.delete() doesn't throw an IOException, it returns a boolean check into if condition
if(file.delete())
{
System.out.println("File deleted successfully");
}
else
{
System.out.println("Failed to delete the file");
}

Related

Getting error "cannot find symbol class". Why?

Here's a program I've writing in Android Studio to write a CSV file.
I keep receiving the error "Cannot find symbol class".
I need help resolving that.
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If that is your complete program it can't compile because each file in Java needs to be a class and you didn't indicate it is a class. And if the class is to be invoked from the command line instead of just instantiated by another class, then you need to name your main entry point.
I've added those things, but have not compiled it. The compiler may generate other errors if the code isn't perfect.
See how that goes and then if you're still stuck update the question with more details and or ask a new more specific question. If this answer helps at all, please give it an up vote.
import java.io.*;
public class WriteCSV
{
public static void main(String args[])
{
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

ObjectInputStream gives IOException when readObject() is called

I'm trying to copy a file with .dat extension from a certain directory decided by the user into the project directory. When I try to read the saved object selected by the user, the program always gives IOException.
File f = new File(chooser.getSelectedFile().getPath());
if(f.exists() && !f.isDirectory()) {
FileInputStream flusso= null;
ObjectInputStream leggiObj=null;
try {
flusso = new FileInputStream(chooser.getSelectedFile().getPath());
System.out.println(chooser.getSelectedFile().getPath());
leggiObj = new ObjectInputStream(flusso);
if (leggiObj.readObject().getClass().equals(DatiProgresso.class)) {
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();//<----THIS LINE GIVES THE EXEPTION
leggiObj.close();
flusso.close();
System.out.println("Ciao");
FileOutputStream fop = new FileOutputStream("salvataggi/" + dp.getNome() + ".dat");
ObjectOutputStream scriviObj = new ObjectOutputStream(fop);
scriviObj.writeObject(dp);
scriviObj.flush();
fop.close();
} else {
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (HeadlessException ex) {
System.out.println("HeadlessException");
ex.printStackTrace();
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("IOException");
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException");
ex.printStackTrace();
}
}
}
else
{
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error" ,JOptionPane.ERROR_MESSAGE);
}
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();
This line gives the exception.
leggiObj.readObject().getClass().equals(DatiProgresso.class) - here you read your object from the data stream. On next line you attempt to read 2nd object from the stream. If there is no another object then stream fails.

StreamCorruptedException: invalid stream header: 79737200 when reading objects from a file

I create a client similarity, where clients register an account (an object is created) which is stored in a file.
Objects are written to the file as required, I override the writeStreamHeader() method. But when I try to read them all, their file throws an exception.
Write the objects to the file here.
public static void saveAccaunt(LoginAndPass gamers) {
boolean b = true;
FileInputStream fis = null;
try{
fis = new FileInputStream("student.ser");
fis.close();
}
catch (FileNotFoundException e)
{
b = false;
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream("student.ser",true);
ObjectOutputStream os = null;
if(b = true){
os = new AppendingObjectOutputStream(fileOutputStream);
System.out.println("Объект добавлен!");
}else {
os = new ObjectOutputStream(fileOutputStream);
System.out.println("Создан");
}
os.writeObject(gamers);
os.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("student.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
test = new ArrayList<>();
while (true){
test.add(objectInputStream.readObject());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(test.get(0));
}
Here is the error log for the exception thrown:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
at java.io.ObjectInputStream.(ObjectInputStream.java:358)
at Registratsiya.AllGamers.main(AllGamers.java:48)
Exception in thread "main" java.lang.NullPointerException
at Registratsiya.AllGamers.main(AllGamers.java:61)

Why is my .bin file being overwritten when I read data from it? (Java)

I made my own data structure called a User. I am trying to store Users in a .bin file using FileInputStream and FileOutputStream. I am successfully storing a single user when a button is pressed, but then when I close the application and go to read my Users and recognize login info, the .bin file turns blank.
I know that the .bin file is not empty after the program closes, but then when I try to read the file I get a EOFException. Here is my code to read objects from the file:
public void loadUsers() {
try {
ObjectInputStream ois = new ObjectInputStream(fi);
boolean endOfFile = false;
while (!endOfFile) {
try {
System.out.println("loaded a user!");
User person = (User) ois.readObject();
Users.addUser(person);
} catch (EOFException e) {
endOfFile = true;
ois.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Here is my code to write objects to the file:
public void storeUser(User person) {
boolean endOfFile = false;
try {
new ObjectInputStream(fi).readObject();
} catch (EOFException e) {
endOfFile = true;
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
if (!endOfFile) {
System.out.println("Appending!");
try {
AppendingObjectOutputStream aos = new AppendingObjectOutputStream(fo);
aos.writeObject(person);
aos.flush();
aos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Writing a new file!");
try {
ObjectOutputStream oos = new ObjectOutputStream(fo);
oos.writeObject(person);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AppendingObjectOutputStream is just a small subclass of ObjectOutputStream I made that overwrites writeStreamHeader() so that there is no header placed in my file when try to write more users. I don't think this is related to the problem because I have yet to write a User onto a file with Users already written on it.

File is being recreated even though it already exists

How does this code delete the file I had and makes a new one??
public void actualizaJTextArea(String cliente){
mensagens.setText("");
Scanner scanner = null;
File file = createFile(cliente + "chatswith.txt");
try {
scanner = new Scanner(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(...)
scanner.close();
}
public static File createFile(String s){
File file = new File(s);
if(!file.exists()){
try {
boolean b = file.createNewFile();
System.out.println(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
Does the method createNewFile() do this?
Thanks and I'm sorry if this has been asked before I just can't find it.
EDIT
I am also using createFile() in here to write in it but the use is the same so i guess that can't be it:
public void recebeMensagem(boolean b){
while(true){
Mensagem m = null;
try {
m = (Mensagem)input.readObject();
System.out.println("Mensagem Recebida:"+m);
} catch (ClassNotFoundException e){
} catch (IOException e) {
try {
input.close();
System.out.println("Server desligou...");
break;
} catch (IOException e1) {
}
}
if(m != null){
for(Mensagens mensagens:v){
for(String string: m.getReceivers()){
if (mensagens.getCliente().equals(m.getAuthor()) && mensagens.getContacto().equals(string)){
mensagens.actualizaJTextArea(cliente);
}
}
}
for(String Str :m.getReceivers()){
PrintWriter p = null;
File file = Mensagens.createFile(cliente + "chatswith.txt");
try {
p = new PrintWriter(new FileWriter(file));
p.append(m.getAuthor()+"</<"+Str+"</<"+m.getText()+"\n");
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
createNewFile() is atomic and it will not delete the file if it is present. Please look at the boolean output, it should be false if your file exists already.
EDIT
add append parameter to FileWriter. It is overwriting every time.
FROM
p = new PrintWriter(new FileWriter(file));
TO
p = new PrintWriter(new FileWriter(file,true));

Categories

Resources