Delete Temp File in Java - java

Am having the below code , creating a Temp file and read that and deleting the file.
But after deletion also file available to read .Please help to find wrong with my code....
public static void main(String args[]) throws Exception
{
Calendar mSec = Calendar.getInstance();
String fileName="hubname_"+"msgname_"+mSec.getTimeInMillis();
String str ="Hello How are you doing .......";
System.out.println("fileName :"+fileName);
File f = File.createTempFile(fileName, ".xml");
FileWriter fw = new FileWriter(f);
fw.write(str);
fw.flush();
fw.close();
printFileContent(f);
f.delete();
printFileContent(f);
}
public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
}
Output :
fileName :hubname_msgname_1358655424194
stringBuilder.toString() :Hello How are you doing .......
stringBuilder.toString() :Hello How are you doing .......

You should close reader in printFileContent. File.delete cannot delete an opened file (at least on Windows, see Keith Randall's comment below) in which case it returns false. You could check if delete was successful
if (!f.delete()) {
throw new IOException("Cannot delete " + f);
}
The following comment was added to File.delete API in Java 7
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

public static void printFileContent(File f)throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader(f));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
if(reader != null){
reader.close();
}
}

Related

EOF not working in data files to save value

public static void main(String[] args) throws IOException {
InputStream istream;
int c;
final int EOF = -1;
istream = System.in;
FileWriter outFile = new FileWriter("C:/Users/boamb/Documents/NetBeansProjects/DSA_BSE20BFT/src/week7/Data.txt",true);
BufferedWriter bWriter = new BufferedWriter(outFile);
System.out.println("Enter fruits to store in data File – Press Ctrl+Z to end ");
while ((c = istream.read()) != EOF)
bWriter.write(c);
bWriter.close();
}
Hi everyone, I am trying to insert data in a file through the system output in the NETBEANS IDE but the issue is when i am pressing CTRL+Z it is not working, the program is still running and when i stop it manually there are no data saved in the file. This is my piece of code.
Actually I don't understand what is the reason for relying on EOF when your logic says "Enter fruits". I mean you should read a string, not a byte-by-byte and in this case terminator will be also some string value, "end" for example:
public static void main( String[] args ) throws IOException{
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
FileWriter outFile = new FileWriter( "C:/Users/boamb/Documents/NetBeansProjects/DSA_BSE20BFT/src/week7/Data.txt", true );
try ( BufferedWriter bWriter = new BufferedWriter( outFile ); ){
String line;
while( true ){
System.out.println( "Enter fruits to store in data File – Enter 'end' to end " );
line = br.readLine();
if( "end".equals( line ) ){
break;
}
bWriter.write( line );
bWriter.newLine();
}
bWriter.flush();
}
}

merge file and delete the old file

I have been trying to merge two files into new file and below code does it job. But after the merge i want to delete the old files. The code I am using to delete files just delete 1 file (file2) not the both of them.
public static void Filemerger() throws IOException
{
String resultPath = System.getProperty("java.io.tmpdir");
File result = new File(resultPath+"//NewFolder", "//file3.txt");
// PrintWriter object for file3.txt
PrintWriter pw = new PrintWriter(result);
// BufferedReader object for file1.txt
BufferedReader br = new BufferedReader(new FileReader(resultPath+"file1.txt"));
String line = br.readLine();
// loop to copy each line of
// file1.txt to file3.txt
while (line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush();
br = new BufferedReader(new FileReader(resultPath+"file2.txt"));
line = br.readLine();
// loop to copy each line of
// file2.txt to file3.txt
while(line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush();
// closing resources
br.close();
pw.close();
File dir = new File(resultPath);
FileFilter fileFilter1 = new WildcardFileFilter(new String[] {"file1.txt", "file2.txt"}, IOCase.SENSITIVE);
File[] fileList1 = dir.listFiles(fileFilter1);
for (int i = 0; i < fileList1.length; i++) {
if (fileList1[i].isFile()) {
File file1 = fileList1[i].getAbsoluteFile();
file1.delete();
}
}
}
I also try this code to delete the file1 as above code delete the file2:
Path fileToDeletePath = Paths.get(resultPath+"file1.txt");
Files.delete(fileToDeletePath);
but it throws an exception that Exception in thread "main" java.nio.file.FileSystemException: C:\Users\haya\AppData\Local\Temp\file1: The process cannot access the file because it is being used by another process.
Closing the streams as suggested in the comments will fix. However you are writing a lot of code which is hard to debug / fix later. Instead simplify to NIO calls and add try with resources handling to auto-close everything on the way:
String tmp = System.getProperty("java.io.tmpdir");
Path result = Path.of(tmp, "NewFolder", "file3.txt");
Path file1 = Path.of(tmp,"file1.txt");
Path file2 = Path.of(tmp,"file2.txt");
try(OutputStream output = Files.newOutputStream(result)) {
try(InputStream input = Files.newInputStream(file1)) {
input.transferTo(output);
}
try(InputStream input = Files.newInputStream(file2)) {
input.transferTo(output);
}
}
Files.deleteIfExists(file1);
Files.deleteIfExists(file2);

Writing with a PrintWriter to a file doesn't come out right

public static void doubleSpace(String fileName) {
try {
FileReader reader = new FileReader(fileName);
Scanner in = new Scanner(reader);
String outputFileName = fileName.charAt(0) + ".ds";
PrintWriter pOut = new PrintWriter(outputFileName);
// Opening of files for input and output
while (in.hasNextLine()) {
String line = in.nextLine();
pOut.println(line + "\n");
pOut.print("\n");
// System.out.println(line + "\n"); //Test
}
pOut.close(); // Close the files if they have been opened.
} catch (Exception e) {
}
}
So basically my input file contains
a
b
c
and my output file should look like
a
b
c
However, my output file always contains only abc.
Any help would be much appreciated!
Use a BufferedWriter. It has a .newLine() method. This method will use the platform's default line separator.
And use a BufferedReader. It has a .readLine() method.
Example:
// NOTE: you should really be using UTF-8
final Charset charset = Charset.defaultCharset();
final Path src = Paths.get(filename);
final Path dst = Paths.get(filename + ".ds");
String line;
try (
final BufferedReader reader = Files.newBufferedReader(src, charset);
final BufferedWriter writer = Files.newBufferedWriter(dst, charset);
) {
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
writer.newLine();
}
}
You are likely useing the wrong character(s) for new line for your plattform. Use
System.getProperty("line.separator");
to get the right value.

Compare a text file line by line with a dynamic variable

I have a text file sample.txt which have following lines
sample1.txt
test.ppt
example.doc
content.pdf
I have a dynamic variable called field (example phpcookbook.pdf,sample1.txt) it should compare with each line in sample.txt file and if the text file does not contain the field it should append to sample.txt. I have tried the following code but it's not working:
File insert=new File(sample.txt);
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
while ((strLine = br.readLine()) != null) {
if(!strLine.equals(field)) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field);
bw.close();
}
}
I should get the following output
sample1.txt
test.ppt
example.doc
content.pdf
phpcookbook.pdf
How to compare a text file line by line with a dynamic variable?
If I understand the question correctly, this is what you need:
File insert = new File("sample.txt");
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
Boolean hasLine = false;
while ((strLine = br.readLine()) != null) {
if(strLine.equals(field)) {
hasLine = true;
break;
}
}
br.close();
if (!hasLine) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field + "\n"); // assumes field does not already have a newline
bw.flush();
bw.close();
}
Notice the break;. This will discontinue the while loop, since you already have the answer to what you are looking for.
Your original code was doing:
for every line:
Do I equal field?
Yes: goto next line
No: append field to file and goto next line
But what you WANTED to know was whether or not field appeared in the file at all, not in each line.
You should use Commons IO.
See this working example
package training;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class TestFile {
/**
* #param args
* #throws IOException
*/
private static String field = "phpcookbook.pdf";
private static String fileContent;
public static void main(String[] args) throws IOException {
boolean found = false;
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
if (line.equals(field)) {
found = true;
break;
}
}
if (!found) {
fileContent = FileUtils.readFileToString(file);
fileContent += "\n" + field;
}
FileUtils.write(file, fileContent);
}
}
You should do something like this:
File insert = new File("sample.txt");
boolean isStringPresent = false;
BufferedReader br = new BufferedReader(new FileReader(insert));
String strLine;
while ((strLine = br.readLine()) != null) {
if (strLine.equals(field)) {
isStringPresent = true;
}
}
if(!isStringPresent) {
FileWriter fw = new FileWriter(insert, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(field);
bw.close();
}
No answer since you ask for Java, but just to illustrate the power of Unix shell tools:
v=phpcookbook.pdf
grep $v in.txt
[[ $? -eq 1 ]] && echo $v >> in.txt

Java read in single file and write out multiple files

I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}

Categories