After reading a file, I'm trying to delete it, but the following error appears:
java.io.IOException: Unable to delete file test.zip at
org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) at
org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044)
at org.apache.commons.io.FileUtils.deleteDirectory
(FileUtils.java:977)
Here is my code. I've been careful to close the InputStream in the finally clause and only then call the method that deletes the file, but even then I can only delete it when I stop the program.
InputStream is = null;
try {
is = new URL(filePath).openStream(); // filePath is a string containing the path to the file like http://test.com/file.zip
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
String xml = sb.toString(); // this code is working, the result of the "xml" variable is as expected
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
removeFileAndFolder(absolutePath);
}
private void removeFileAndFolder(String absolutePath) {
new Thread(new Runnable() {
#Override
public void run() {
try {
String folder = getFolder(absolutePath); // this method just get the path to the folder, because I want to delete the entire folder, but the error occurs when deleting the file
FileUtils.deleteDirectory(new File(folder));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
After some tests I discovered that I can manually delete the file just before the line "is = new URL (filePath) .openStream ();". After it, and even after the line "is.close ();" I can not delete the file manually unless I stop the program.
I got it. I was opening the file by the url (is = new URL(filePath).openStream();), and trying to delete it by absolute path. I changed it to "is = new FileInputStream(absoluteFilePath);" and it works!
Related
New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
File exportFile = null;
try {
if (CollectionUtils.isEmpty(receipts)) {
return "";
}
exportFile = File.createTempFile(fileName, ".csv");
exportFile.deleteOnExit();
try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
try {
fw.write("test");
} finally {
fw.close();
}
}
return exportFile.getPath();
} catch (Exception ex) {
logger.error("Error exporting report. ", ex.getMessage());
}
return "";
}
String getStreamFromPath(String filePath) {
try {
File downloadFile = new File(filePath);
fileInputStream = new FileInputStream(downloadFile);
return SUCCESS;
} catch (IOException e) {
log.error(e.getMessage(), e);
return ERROR;
}
}
This is really weird, when i test in another server it works totally fine. Any ideas?
i use eclipse
and my structure looks like this:
TSG-jar
->src
->myBean.java (here i need a path)
and another one web application
TSG-war
->WebContent
->js
->boot.js
so they are both in the same workspace
I call the boot.js file from TSG-war in my TSG-jar (from myBean.java), and i need a path...but i have no idea how to do it...
In myBean.java i got this code:
private String getSrc(String path) {
try {
BufferedReader in = new BufferedReader(new FileReader(path));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
return sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I need the path of the javaScript.js file to send it to the function...
can u help me?
i tried:
String s = "..\\..\\..\\TSG-war\\WebContent\\js\\boot.js"
String s = "\\..\\..\\..\\TSG-war\\WebContent\\js\\boot.js"
String s = "\\..\\..\\..\\..\\TSG-war\\WebContent\\js\\boot.js"
System.out.println(getSrc(s));
its always null...
where is the error?
My code is creating a file to save data into, but it's also overwriting the previous data that was saved previously under that same file name. How do I modify my code in order to save the new data without affecting the old one? I want my data to be saved with a line that separates the old one. Here is my code part of saving:
public void buttonSave(View view) {
File file = new File(path + "/Data.txt");
String[] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save(file, saveText);
}
You could try reading the data from your file into a String and then add new text to the string. After that save the file with the newly added info and you're done. Here's a sample on how to read the file:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Simple Question I know - but my android app simply can´t find my CSV file. I´ve placed the file here:
and access it with this code:
public void getFragenfromCSV(){
AssetManager a = getAssets();
BufferedReader reader = null;
try {
InputStream is = a.open("fragenbronze.csv");
reader = new BufferedReader(new InputStreamReader(s));
} catch (IOException e) {
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
e.printStackTrace();
}
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
System.out.println(RowData[0]);
}
}
catch (IOException ex) {
// handle exception
}
}
On running the app I always get the IOException from the catch part.
you have to place it in
src/main/assets
never put something you want to keep in build/ as this get's removed with clean
Project Structure with assets folder
You are going inside build but actually you have to go inside src/main/assets.
hey guys i've this program to read a file
public static String readFileAsString(String filename){
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(filename));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
reader.close();
return sb.toString();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File Not Found","ERROR",JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
and this is my constructor
public tsst() {
initComponents();
JOptionPane.showMessageDialog(null, readFileAsString("test.txt"),"Succes",JOptionPane.DEFAULT_OPTION);
}
and the file is in the application project if i run the file from Netbeans it's work normaly i got what i need but if i build the application so i got the JAR File and i run it i got Error FILE NOT FOUND
and the same in the Writing
public static void writeFile(String canonicalFilename, String text){
File file = new File (canonicalFilename);
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(file));
out.write(text);
out.close();
} catch (IOException ex) {
Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
}
}
Add this line in your readFileAsString method
System.out.println("Current Directory:"+ new File(".").getAbsolutePath());
That will tell you what your application's current directory is. Put your test.txt file in that same directory and you should be able to read it. I'd imagine the output would be different between Netbeans (where you know the file is expected) and when you run the Jar (which could be anywhere).