java how to check if file exists and open it? - java

how to check if file exists and open it?
if(file is found)
{
FileInputStream file = new FileInputStream("file");
}

File.isFile will tell you that a file exists and is not a directory.
Note, that the file could be deleted between your check and your attempt to open it, and that method does not check that the current user has read permissions.
File f = new File("file");
if (f.isFile() && f.canRead()) {
try {
// Open the stream.
FileInputStream in = new FileInputStream(f);
// To read chars from it, use new InputStreamReader
// and specify the encoding.
try {
// Do something with in.
} finally {
in.close();
}
} catch (IOException ex) {
// Appropriate error handling here.
}
}

You need to create a File object first, then use its exists() method to check. That file object can then be passed into the FileInputStream constructor.
File file = new File("file");
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
}

You can find the exists method in the documentation:
File file = new File(yourPath);
if(file.exists())
FileInputStream file = new FileInputStream(file);

Related

Sub Directories under getCacheDir()

I'm trying to create sub directories in my apps cache folder but when trying to retrieve the files I'm getting nothing. I have some code below on how I created the sub directory and how I'm reading from it, maybe I'm just doing something wrong (well clearly I am lol) or maybe this isn't possible? (though I haven't seen anywhere that you can't). thank you all for any help!
creating the sub dir
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
File file2 = new File(file, each_filename);
Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();
stream = new FileOutputStream(file2);
stream.write(bytes);
reading from it
File file = new File(context.getCacheDir(), "SubDir");
File newFile = new File(file, filename);
Note note;
if (newFile.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = new FileInputStream(new File(file, filename));
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
I've also tried with this and nothing
String file = context.getCacheDir() + File.separator + "SubDir";
I don't see anywhere in the code you posted where you actually create the sub-directory. Here's some example code to save a file in a sub-directory, by calling mkdirs if the path doesn't yet exist (some parts here need to be wrapped in an appropriate try-catch for an IOException, but this should get you started).
File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;
if( !cachePath.exists() ) {
// mkdir would work here too if your path is 1-deep or
// you know all the parent directories will always exist
errs = !cachePath.mkdirs();
}
if(!errs) {
FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
fout.write(bytes.toByteArray());
fout.flush();
fout.close();
}
You need to make your directory with mkdir.
In your code:
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);

Return Zip File from ZipOutputStream in Java

I have a function which creates a Zip file from a list of files. Is it possible to return the Zip file without it being saved on the disk? I need the file as I have to use the zip file as a parameter for another function. I am not sure of the ByteStream would be an option for me.
public File compressFileList(List<File> fileList,String fileName) {
FileOutputStream fileOutputStream=null;
ZipOutputStream zipOutputStream=null;
FileInputStream fileInputStream=null;
String compressedFileName=fileName +".zip";
if(fileList.isEmpty())
return null;
try
{
fileOutputStream = new FileOutputStream(compressedFileName);
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
for (File file: fileList) {
fileInputStream = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
byte[] tmp = new byte[4*1024];
int size = 0;
while((size = fileInputStream.read(tmp)) != -1){
zipOutputStream.write(tmp, 0, size);
}
zipOutputStream.flush();
fileInputStream.close();
}
zipOutputStream.close();
return compressedFile; //This is what I am missing
}
catch (FileNotFoundException e)
{
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
EDIT : adding the use case
The idea is to create a zip file and use the CreateClassifierOptions method of VisualRecognition Service of Watson.
classifierOptions = new CreateClassifierOptions.Builder()
.classifierName("Santa")
.addClass("Santa", new File("C:\\app\\GitRepo\\images\\beagle.zip"))
.negativeExamples(new File("C:\\app\\GitRepo\\images\\nosport.zip"))
.build();
The builder accepts the zip file as the parameter.
Understanding
Based on the explanation from Alexandre Dupriez, I think it is better to store the file at some place on the hard disk.
You should be able to use a ByteArrayOutputStream instead of a FileOutputStream:
zipOutputStream = new ZipOutputStream(new ByteArrayOutputStream());
The difficulty here is to provide a File to the method consuming the zip file. The java.io.File does not provide an abstraction which allows you to manipulate in-memory files.
The java.io.File abstraction and java.io.FileInputStream implementation
To simplify, if we had to boil down what the File abstraction is, we would see it as a URI. And therefore, to be able to build an in-memory File, or at least mimic it, we would need to provide an URI which would then be used by the consumer of the File to read its content.
If we look at the FileInputStream which the consumer is likely to use, we can see that it always ends up with a native call which gives us to possibility whatsoever to abstract a FileSystem for in-memory files:
// class java.io.FileInputStream
/**
* Opens the specified file for reading.
* #param name the name of the file
*/
private native void open0(String name) throws FileNotFoundException;
It would be easier if there was a possibility to adapt the consumer to accept an InputStream, but from your problem statement I guess this is not possible.
API call
Your requirement is to provide a File to the Watson Visual API.
Could you please provide the API method you need to call?
public void compressFileList(List<File> fileList, OutputStream outputStream)
throws IOException {
try (ZipOutputStream zipOutputStream =
new ZipOutputStream(new BufferedOutputStream(outputStream));
for (File file: fileList) {
try (FileInputStream fileInputStream = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
byte[] tmp = new byte[4*1024];
int size = 0;
while((size = fileInputStream.read(tmp)) != -1){
zipOutputStream.write(tmp, 0, size);
}
zipOutputStream.flush();
} catch (FileNotFoundException e) { // Maybe skip not found files.
Logger.log(Level.INFO, "File not found {}", file.getPath());
}
}
}
}
Usage:
if (fileList.isEmpty()) {
...
return;
}
try {
compressFileList(fileList, servletRequest.getOutputStream())) {
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
}

How to change getResource to getResourceAsStream

The program runs well with getResource, but after made it into the jar file, it has FileNotFoundException. It cannot find out test.conf.
My code is
URL url = getClass().getResource("test.conf");
File fin = new File(url.getPath());
FileInputStream fis = null;
try {
fis = new FileInputStream(fin);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I think I can fix the problem by using getResourceAsStream. But I'm not sure how to change getResource to getResourceAsStream.
Your example suggests that your reading code already works on a FileInputStream. You should be able to make it work with the more general InputStream. This will allow you to just pass the result of getResourceStream() to your reading code, without having to worry about Files.
So:
URL url = getClass().getResource("test.conf");
File fin = new File(url.getPath());
FileInputStream fis = new FileInputStream(fin);
ReadResourceFromStream(fis);
Changes to:
InputStream is = getClass().getResourceAsStream("test.conf");
ReadResourceFromStream(is);

File not created in Java (Eclipse)

So I've been doing like the simplest thing ever. Create a text file for a Java application. Just directly in the C directory:
File file = new File("C://function.txt");
System.out.println(file.exists());
The file never shows up though, I changed the slashes, changed the path, nothing. Could anyone help me out here?
There are many methods to create a new file with java : (You should firstly verify the permission to create a file in that folder c: )
String path = "C:"+File.separator"function.txt";
File f = new File(path);
f.mkdirs();
f.createNewFile();
__ or
try {
//What ever the file path is.
File f = new File("C:/function.txt");
FileOutputStream is = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("Line 1!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file function.txt");
}
After Java 7, you should use the new I/O API instead of the File class to create new files.
Here is an example:
Path path = Paths.get("C://function.txt");
try {
Files.createFile(path);
System.out.println(Files.exists(path));
} catch (IOException e) {
e.printStackTrace();
}
You are just creating a File object, not a file itself. So in-order to create new file you need use below command:
file .createNewFile();
This would create your file under C:\ drive. Maybe you can also check if it is already exsits and handle exception etc.
If the file is not exist you can create a new file like:
if(!file.exists()) {
try {
file.createNewFile();
System.out.println("Created a new File");
} catch (IOException e) {
e.printStackTrace();
}
}
The simplest way to do this:
String path = "C:"+File.separator+"function.txt";
File file = new File(path);
System.out.println(file.exists());
try this:
File file = new File("C://function.txt");
if (!file.isFile())
file.createNewFile();
Try this
File file = new File("C:/test.text");
f.createNewFile();

Creating a file dynamically through jsp

I have a block of jsp code like this. Here blockerdata, criticaldata, majordata and minordata are stringbuilder strings and their value is appended through a loop and value is assigned dynamically. Now I'm tryong to write them into an xml file like this.
<%
System.out.println(blockerdata);
System.out.println(criticaldata);
System.out.println(majordata);
System.out.println(minordata);
try
{
File file1 = new File("WebContent/criticaldata.xml");
File file2 = new File("WebContent/majordata.xml");
File file3 = new File("WebContent/minordata.xml");
File file4 = new File("WebContent/blockerdata.xml");
FileOutputStream fop1 = new FileOutputStream(file1);
FileOutputStream fop2 = new FileOutputStream(file2);
FileOutputStream fop3 = new FileOutputStream(file3);
FileOutputStream fop4 = new FileOutputStream(file4);
// if file doesnt exists, then create it
if (!file1.exists()) {
file1.createNewFile();
}
if (!file2.exists()) {
file2.createNewFile();
}
if (!file3.exists()) {
file3.createNewFile();
}
if (!file4.exists()) {
file4.createNewFile();
}
// get the content in bytes
byte[] contentInBytes1= criticaldata.toString().getBytes();
byte[] contentInBytes2= majordata.toString().getBytes();
byte[] contentInBytes3= minordata.toString().getBytes();
byte[] contentInBytes4= blockerdata.toString().getBytes();
fop1.write(contentInBytes1);
fop2.write(contentInBytes1);
fop3.write(contentInBytes1);
fop4.write(contentInBytes1);
fop1.flush();
fop2.flush();
fop3.flush();
fop4.flush();
fop1.close();
fop2.close();
fop3.close();
fop4.close();
}
catch ( IOException e)
{
}
%>
Problem is, the code doesn't seem to be working. I tried to do it using printwriter also but
the files are not being generated. Also I want to rewrite the file if it already exists. Can somebody please help me on how to do this ?

Categories