delete file after reading into inputstream - java

I am trying to retrieve a video stream from a file stored locally. After reading into an inputstream, I am trying to delete the file but it does not allow this to happen. I understand that I need to close the stream, but I need to pass this stream on to a webserver call. Any ideas on how to best approach this:
InputStream is = new FileInputStream("\\Location\\file.txt");
File f = new File("\\Location\\file.txt");
if(f.delete()) {
System.out.println("success");
} else {
System.out.println("failure");
}

Try delete on the Finally block
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class DeleteFile extends FileInputStream {
File file;
public DeleteFile(String s) throws FileNotFoundException {
this(new File(s));
}
public DeleteFile(File file) throws FileNotFoundException {
super(file);
this.file = file;
}
public void close() throws IOException {
try {
super.close();
} finally {
if (file != null) {
file.delete();
file = null;
}
}
}
}

Here is what happens in the constructor FileInputStream(File file) which your constructor delegates to:
public FileInputStream(File file) throws FileNotFoundException {
//some checks of file objects omitted here
fd = new FileDescriptor();
fd.attach(this);
open(name); //native method opening the file for reading
}
calling FileInputStream.close() releases the file descriptor created in the constructor and calls native method to close opened file.
After the call to close() you will be able to delete the file.
See source here.

Files.newInputStream(yourFile,StandardOpenOption.DELETE_ON_CLOSE) seems to be a better option.

Related

Java read CSV file ,contents not write in new CSV file

package com;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import com.opencsv.CSVWriter;
import com.opencsv.CSVReader;
public class Sample2 {
public static void main(String args[]) throws IOException
{
CSVReader csvReader = null;
String[] employeeDetails ;
CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv",true));
csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
try
{
employeeDetails = csvReader.readNext();
while ((employeeDetails = csvReader.readNext()) != null ) {
System.out.println(Arrays.toString(employeeDetails));
csvWriter.writeNext(employeeDetails);
}
}catch(Exception ee)
{
ee.printStackTrace();
}
}
}
I have my above java code
It read data from source.csv file and also display in the console .
It created myfile.csv ,but same contents it didn't write in the csv file
Anyone have any idea on this
CSVWriter implements Flushable.Working Solution is already present in #Stephan Hogenboom's answer. I will answer why didn't it write in your case,
From the javadocs of Flushable interface,
A Flushable is a destination of data that can be flushed. The flush
method is invoked to write any buffered output to the underlying
stream.
For performance reasons, all data is to be written into a Buffer instead of File temporarily. Once you call the flush() method, it flushes the data already present in the buffer into your file(this is where disk I/O happens, not when you call writeNext() ).
As mentioned on doc of flush() in java.io.Writer.
Flushes the stream. If the stream has saved any characters from the
various write() methods in a buffer, write them immediately to their
intended destination.
The issue is that you don't close your output resources, try this code:
public static void main(String args[]) throws IOException {
String[] employeeDetails;
try (CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv", true));
CSVReader csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
) {
while ((employeeDetails = csvReader.readNext()) != null) {
System.out.println(Arrays.toString(employeeDetails));
csvWriter.writeNext(employeeDetails);
}
}
catch (Exception ee) {
ee.printStackTrace(); //perhaps you should also log the error?
}
}
Also take a look at this question Is closing the resources always important?

Unable to Read Text File in Java using FileReader and BufferedReader, possible reasons?

Here From the start() method i called the loadMap(filename) method with a text file.But i don't know why though the loadMap() is called but the FileReader and BufferedReader doesn't working. and the text commented below this two File reader's Statement
System.out.print("INside loadMap()"); doesn't printing in the console and the text File isn't reading. What's the problem here occur actually? Help someone please.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DemoClass {
public static void main(String[] args) {
start();
}
public static void start() {
try {
System.out.print("Pobon File Inside");
loadMap("data\\map1.txt");
} catch (Exception e) {
// TODO: handle exception
}
}
private static void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
FileReader fReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fReader);
System.out.print("INside loadMap()");
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
}
}
System.out.print("INside loadMap()");
}
}
If System.out.print("INside loadMap()") is never called, then an IOException must be thrown when creating the FileReader.
In other words, the file you entered as the parameter when calling loadMap() (data\map1.txt) doesn't exist. You should consider retrieving the file in a different manner, such as placing it in a source folder and then calling getClass().getResource()

I want to create a class to create a file, and use main class to check if that file is created, but my code fail. (Java)

public class Fileverifynanoha
{
private File fileext;
private Path filepath;
public Fileverifynanoha()//this class wants to create a file, write something, and close it.
{
filepath = Paths.get("./txttest.txt");
Charset charset = Charset.forName("US-ASCII");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
try (BufferedWriter filewriter = Files.newBufferedWriter(filepath,charset))
{
filewriter.write(s,0,s.length()-1);
}
catch(IOException e)
{
System.err.println(e);
}
}//end of this class
/**
* #param args the command line arguments
*/
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
if (filetxt.exists()&&!filetxt.isDirectory())//object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Here is the code. I want to use the class I create to create a file, write something. Then, I use main class to check if that file exist.
However, I don't know why, but the main class does not recognise my (maybe) created file. Could anyone tell me how to link them together?
I know there may be some minor bugs in this program. I will fix that later.
Thanks.
You never called your constructor.
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha fvn = new Fileverifynanoha();
if (fvn.filetxt.exists()&&!fvn.filetxt.isDirectory())
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Your issues:
Didn't create instance of class.
Didn't init File file, so it would be null always.
Better use utf-8 for plain text file.
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Fileverifynanoha {
private File file;
private Path path;
public Fileverifynanoha(String fp) {
this.path = Paths.get(fp);
this.file = path.toFile();
}
public void createFile()// this class wants to create a file, write something, and close it.
{
Charset charset = Charset.forName("UTF-8");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
BufferedWriter filewriter = null;
try {
filewriter = Files.newBufferedWriter(path, charset);
filewriter.write(s, 0, s.length() - 1);
filewriter.close();
} catch (IOException e) {
System.err.println(e);
}
}// end of this class
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)// the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha f = new Fileverifynanoha("./txttest.txt");
f.createFile();
if (f.file.exists() && !f.file.isDirectory())// object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
} else {
System.out.println("File does not exist.");
}
}
}

Cannot append data to a binary file with code?

import java.io.FileOutputStream;
import java.io.File;
public class AppendBinaryFile
{
public static void main (String[] args)
{
FileOutputStream toFile = null;
try
{
toFile = new FileOutputStream(new File("numbers.dat"), true);
toFile.write(15);
toFile.write(30);
toFile.close();
}
catch (Exception e)
{
}
}
}
I run another program to get the data from a binary file after running the program but data in the binary file does not change. What is wrong with the code?
You need to close your file output stream I believe.

How to access and read a .txt file from a runnable jar

How can i load a text file with a runnable .jar file, It works fine when it's not jarred but after i jar the application it can't locate the file. Here's what i'm using to load the text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PriceManager {
private static Map<Integer, Double> itemPrices = new HashMap<Integer, Double>();
public static void init() throws IOException {
final BufferedReader file = new BufferedReader(new FileReader("prices.txt"));
try {
while (true) {
final String line = file.readLine();
if (line == null) {
break;
}
if (line.startsWith("//")) {
continue;
}
final String[] valuesArray = line.split(" - ");
itemPrices.put(Integer.valueOf(valuesArray[0]), Double.valueOf(valuesArray[1]));
}
System.out.println("Successfully loaded "+itemPrices.size()+" item prices.");
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (file != null) {
file.close();
}
}
}
public static double getPrice(final int itemId) {
try {
return itemPrices.get(itemId);
} catch (final Exception e) {
return 1;
}
}
}
Thanks for any and all help.
There are two reasons for this. Either the file is now embedded within the Jar or it's not...
Assuming that the file is not stored within the Jar, you can use something like...
try (BufferedReader br = new BufferedReader(new InputStreamReader(PriceManager.class.getResourceAsStream("/prices.txt")))) {...
If the prices.txt file is buried with the package structure, you will need to provide that path from the top/default package to where the file is stored.
If the file is external to the class/jar file, then you need to make sure it resides within the same directory that you are executing the jar from.
if this is your package structure:
Correct way of retrieving resources inside runnable or.jar file is by using getResourceAsStream.
InputStream resourceStream = TestResource.class.getResourceAsStream("/resources/PUT_Request_ER.xml");
If you do getResource("/resources/PUT_Request_ER.xml"), you get FileNotFoundException as this resource is inside compressed file and absolute file path doesn't help here.

Categories

Resources