deleteOnExit not deleting file - java

I have created a few files for temporary use and used them as inputs for some methods. And I called
deleteOnExit()
on all files I created. But one file still remains.
I assume it is because the file is still in use, but doesn't the compiler go to next line only after the current line is done?(Single thread)
While its not a problem practically because of java overwrite, there is only one file always. I would like to understand why it happens and also if I can use
Thread.sleep(sometime);
Edit:-
File x = new file("x.txt");
new class1().method1();
After creating all files(5), I just added this line
x.deleteOnExit(); y.deletOnExit() and so on...
All the files except that last one is deleted.

Make sure that whatever streams are writing to the file are closed. If the stream is not closed, file will be locked and delete will return false. That was an issue I had. Hopefully that helps.
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 java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Test {
public static void main(String[] args) {
File reportNew = null;
File writeToDir = null;
BufferedReader br = null;
BufferedWriter bw = null;
StringWriter sw = null;
List<File> fileList = new ArrayList<File>();
SimpleDateFormat ft = new SimpleDateFormat("yyyymmdd_hh_mm_ss_ms");
try {
//Read report.new file
reportNew = new File("c:\\temp\\report.new");
//Create temp directory for newly created files
writeToDir = new File("c:\\temp");
//tempDir.mkdir();
//Separate report.new into many files separated by a token
br = new BufferedReader(new FileReader(reportNew));
sw = new StringWriter();
new StringBuilder();
String line;
int fileCount = 0;
while (true) {
line=br.readLine();
if (line == null || line.contains("%PDF")) {
if (!sw.toString().isEmpty()) {
fileCount++;
File _file = new File(writeToDir.getPath()
+ File.separator
+ fileCount
+ "_"
+ ft.format(new Date())
+ ".htm");
_file.deleteOnExit();
fileList.add(_file);
bw = new BufferedWriter(new FileWriter(_file));
bw.write(sw.toString());
bw.flush();
bw.close();
sw.getBuffer().setLength(0);
System.out.println("File "
+ _file.getPath()
+ " exists "
+ _file.exists());
}
if (line == null)
break;
else
continue;
}
sw.write(line);
sw.write(System.getProperty("line.separator"));
}
} catch ( Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

In order to close the file that you have opened in your program, try creating an explicit termination method.
Therefore, try writing the following:
public class ClassThatUsesFile {
private String filename;
private BufferReader reader;
public ClassThatUsesFile (String afile) {
this.filename = afile;
this.reader = new BufferReader(new FileReader(afile));
}
// try-finally block guarantees execution of termination method
protected void terminate() {
try {
// Do what must be done with your file before it needs to be closed.
} finally {
// Here is where your explicit termination method should be located.
// Close or delete your file and close or delete your buffer reader.
}
}
}

Related

How to write in a text file in java without deleting the content of the file before

This is code that deletes the content of the file then writes on it
I want to write in the file without deleting the content and write on the last line
import java.io.*;
import java.util.Scanner;
public class SetValues {
public void setNumberPhone(String numberPhone) throws UnsupportedEncodingException {
Scanner input = new Scanner(System.in);
PrintWriter pr = null;
try {
input = new Scanner("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt");
pr = new PrintWriter("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt", "UTF-8");
} catch (FileNotFoundException e) {
System.out.println("Not Open" + e.getMessage());
System.exit(0);
}
if (input.hasNext()) {
pr.println(numberPhone);
}
pr.close();
}
}
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;
OutputStream os = Files.newOutputStream(Paths.get("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt"), APPEND);
PrintWriter pr = new PrintWriter(os);
pr.println("TEXT");
This will create an output stream wherein any output text will be appended to the current contents of the file. You can use the OutputStream to create a PrintWriter. More information can be found at the Java documentation

Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?

I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:
Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
/**
* Created by FakeOwl96 on 3/28/2017.
*/
public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.nextLine();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}
public static void getArea(double n) {
area = n * PI;
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.next();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}
public static void getArea(double n) {
area = n * PI;
}
}
The only change I made is
String fileName = keyboard.next(); from //keyboard.nextLine()
The above code worked for me . Hope this helps.
Add following line after initializing myFile:
myFile.createNewFile(); // if file already exists will do nothing
This is another example of file append line and create new file if file is not exists.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AppendFileDemo2 {
public static void main(String[] args) {
try {
File file = new File("myfile2.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//This will add a new line to the file content
pw.println("");
/* Below three statements would add three
* mentioned Strings to the file in new lines.
*/
pw.println("This is first line");
pw.println("This is the second line");
pw.println("This is third line");
pw.close();
System.out.println("Data successfully appended at the end of file");
} catch (IOException ioe) {
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
This is an example of file append line and create new file if file is not exists.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {
public static void main(String[] args) {
try {
String content = "This is my content which would be appended "
+ "at the end of the specified file";
//Specify the file name and path here
File file = new File("myfile.txt");
/* This logic is to create the file if the
* file is not already present
*/
if (!file.exists()) {
file.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(file, true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();
System.out.println("Data successfully appended at the end of file");
} catch (IOException ioe) {
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Yet, another example, this time with try-with-resources and using the Files class to create the BufferedWriter:
public void write(File file, String text) throws IOException {
Path path = file.toPath();
Charset charSet = StandardCharsets.UTF_8;
OpenOption[] options = new OpenOption[]{
StandardOpenOption.CREATE, // Create a new file if it does not exist
StandardOpenOption.WRITE, // Open for write access
StandardOpenOption.APPEND // Bytes will be written to the end of
// the file rather than the beginning
};
try (BufferedWriter bw = Files.newBufferedWriter(path, charSet, options)) {
bw.write(text);
}
}
The above example is available on GitHub with tests.
You can also use the Files.write method:
public void write(File file, List<String> lines) throws IOException {
Path path = file.toPath();
Charset charSet = StandardCharsets.UTF_8;
OpenOption[] options = new OpenOption[]{
StandardOpenOption.CREATE, // Create a new file if it does not exist
StandardOpenOption.WRITE, // Open for write access
StandardOpenOption.APPEND // Bytes will be written to the end of
// the file rather than the beginning
};
Files.write(path, lines, charSet, options);
}

Replace a word in a file with a new file content

I'm writing a code where in data in a file has to be replaced with another file content.
I know how to use a string Replace() function. but the problem here is, I want to replace a string with a entirely new Data.
I'm able to append(in private static void writeDataofFootnotes(File temp, File fout)) the content, but unable to know how do I replace it.
Below is my code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
public class BottomContent {
public static void main(String[] args) throws Exception {
String input = "C:/Users/u0138039/Desktop/Proview/TEST/Test/src.html";
String fileName = input.substring(input.lastIndexOf("/") + 1);
URL url = new URL("file:///" + input);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
File fout = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/" + fileName);
File temp = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/temp.txt");
if (!fout.exists()) {
fout.createNewFile();
}
if (!temp.exists()) {
temp.createNewFile();
}
FileOutputStream fos = new FileOutputStream(fout);
FileOutputStream tempOs = new FileOutputStream(temp);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
BufferedWriter tempWriter = new BufferedWriter(new OutputStreamWriter(tempOs));
String inputLine;
String footContent = null;
int i = 0;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("class=\"para\" id=\"")) {
footContent = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"<div class=\"tr_footnote\">\n<div class=\"footnote\">\n<sup><a name=\"ftn.$2\" href=\"#f$2\" class=\"tr_ftn\">$4</a></sup>\n"
+ "<div class=\"para\">" + "$6" + "\n</div>\n</div>\n</div>");
inputLine = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"");
tempWriter.write(footContent);
tempWriter.newLine();
}
inputLine = inputLine.replace("</body>", "<hr/></body>");
bw.write(inputLine);
bw.newLine();
}
tempWriter.close();
bw.close();
in.close();
writeDataofFootnotes(temp, fout);
}
private static void writeDataofFootnotes(File temp, File fout) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(temp);
fw = new FileWriter(fout, true);
int c = fr.read();
while (c != -1) {
fw.write(c);
c = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// ...
}
}
}
Here I'm searching for a particular string and saving it in a separate txt file. And once I'm done with the job. I want to replace the <hr /> tag with the entire txt file data.
How can I achieve this?
I'd modify your processing loop as follows:
while ((inputLine = in.readLine()) != null) {
// Stop translation when we reach end of document.
if (inputLine.contains("</body>") {
break;
}
if (inputLine.contains("class=\"para\" id=\"")) {
// No changes in this block
}
bw.write(inputLine);
bw.newLine();
}
// Close temporary file
tempWriter.close();
// Open temporary file, and copy verbatim to output
BufferedReader temp_in = Files.newBufferedReader(temp.toPath());
String footnotes;
while ((footnotes = temp_in.readLine()) != null) {
bw.write(footnotes);
bw.newLine();
}
temp_in.close();
// Finish document
bw.write(inputLine);
bw.newLine();
while ((inputLine = in.readLine()) != null) {
bw.write(inputLine);
bw.newLine();
}
// ... and close all open files

Scraping Google App Store for Meta Data

I am noob in Java trying to to build a scraper in a Java which could do the following things.
Ability to read data from a CSV file.
Use the URIs in that file and scrape the complete App info from the Google Playstore.
Export the scraped data and other meta data from the CSV file into an XML file
Can any one guide me in this how to go from here ?
Till now I have made the following three classes
main.java (This is the main method where I call other two classes)
import java.io.IOException;
public class main {
public static void main(String[] args) throws IOException {
ReadCVS obj = new ReadCVS();
obj.run();
AppInfo obj1 = new AppInfo();
obj1.readFile();
}
}
ReadCVS.java (This file reads the CSV file and give the output in a txt file)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
public class ReadCVS {
public void run() {
// Replace the file path to the appropriate path.
String csvFile = "\\Desktop\\https---play_google_com-store-apps-details-id=.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
File file = new File("\\Desktop\\output.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
System.out.println("URL = " + country[0] + " "
);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
AppInfo.java (This file reads the input from the saved output.txt and tries to out put in the console. But it is not currently working)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class AppInfo {
public void readFile(){
String fileName = "\\Desktop\\output.txt";
//read file into stream, try-with-resources
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem is that whenever I try to run this code the program get hanged and does not terminate.
Can any one help me with my problem ?

Read created at runtime file with java

I create and write a file with a java method, then I want to read this file at runtime with another java method.But it throws java.io.FileNotFoundException error.
How could I fix this error?
Writer output=null;
File file = new File("train.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(trainVal[0] + "\n");
-------------------
and read code
FileInputStream fstreamItem = new FileInputStream("train.tx");
DataInputStream inItem = new DataInputStream(fstreamItem);
BufferedReader brItem = new BufferedReader(new InputStreamReader(inItem));
String phraseItem;
ArrayList<Double> qiF = new ArrayList<Double>();
while ((phrase = br.readLine()) != null) {
//doing somethinh here
}
Use the correct file name. This includes the path to the file. Also make sure that no one deleted the file between those two functions or renamed it.
The following is one of the best and convenient methods to read a file. Go through it instead of using traditional methods.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
final public class Main
{
public static void main(String... args)
{
File file = new File("G:/myFile.txt"); //Mention your absolute file path here.
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner=null;
try
{
scanner = new Scanner(file);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String lineSeparator = System.getProperty("line.separator");
try
{
while(scanner.hasNextLine())
{
fileContents.append(scanner.nextLine()).append(lineSeparator);
}
}
finally
{
scanner.close();
}
System.out.println(fileContents); //Displays the file contents directly no need to loop through.
}
}
You have made a mistake in giving a proper file extension in your code.
FileInputStream fstreamItem = new FileInputStream("train.tx");
Should have been
FileInputStream fstreamItem = new FileInputStream("train.txt");

Categories