Java isn't getting files in a directory - java

System.out.println("READ");
String currentWorldName = "RANDOM";
String propertiesFileDirectory = propertiesFolder + currentWorldName + "/props.properties";
String entitiesFolderDirectory = propertiesFolder + currentWorldName + "/Entities";
try
{
properties.load(new FileInputStream(propertiesFileDirectory));
}
catch (FileNotFoundException e)
{
//Since it doesn't exist either it was deleted by the user or hasn't been created yet.
createNewPropertiesFile();
}
catch (IOException e)
{
outputToLog("IOException when loading properties file for the world: '" + currentWorldName + "'.\n" + e.getStackTrace().toString());
}
//getting values from properties
//Now to read each properties file in Entities
File entitiesFolder = new File(entitiesFolderDirectory);
try
{
List<String> entitiesDirectoryContents = Arrays.asList(entitiesFolder.list());
//Read each file in the entities directory and load it into memory.
for (String entityPropertiesFileName : entitiesDirectoryContents)
{
if (propertiesBelongsToEntityCH(entityPropertiesFileName))
{
//Get properties one way
}
else //The properties file we're working does not belong to CH.
{
//Get properties from the same file a different way
}
}
//This should never be hit since we have the file to read.
catch (FileNotFoundException e)
{
outputToLog("FileNotFoundException when loading entity properties file." + e.getMessage().toString());
}
//I don't know when/if this would be hit. It hasn't happened.
catch (IOException e)
{
outputToLog("IOException when loading entity properties file." + e.getMessage().toString());
}
catch (NullPointerException e)
{
entitiesFolder.mkdirs();
}
This HAS been working, I swear. It just started doing this.
Java keeps claiming that the "entitiesFolder" directory doesn't exist (I check with entitiesFolder.exists()). I have a solution for when that happens as you can see, because while my program is running it definitely can happen. Well it still claims that the folder doesn't exist, over and over.
I'm absolutely positive that it's the right directory because I print the "entitiesFolderDirectory" out to the console. It's correct. I can also be looking at the files inside of that folder and when mkdirs() runs it just deletes them all.
Java bug? This has completely broken my program.

I would write it without throwing a NullPointerException.
File entitiesFolder = new File(entitiesFolderDirectory);
entitiesFolder.mkdirs();
for (String entityPropertiesFileName : entitiesFolder.list()) {
//Do stuff
}
This will always work unless the folder could not be created.

What is the problem with this code? only one curly braces i found is missing else it is working fine.
This will create a dir test in c drive if does not exist else it will list the files in test dir over n over again
String entitiesFolderDirectory = "C:\\test";
File entitiesFolder = new File(entitiesFolderDirectory);
try
{
List<String> entitiesDirectoryContents = Arrays.asList(entitiesFolder.list());
for (String entityPropertiesFileName : entitiesDirectoryContents)
{
System.out.println(entityPropertiesFileName);
}
}catch (NullPointerException e)
{
System.out.println("creating new folder");
entitiesFolder.mkdirs();
}

Related

How to find directory for File Output Stream in Android app?

I have an app which gets data from an Arduino via bluetooth. The data are written into various ArrayLists and saved in files afterwards. Here is the code:
public boolean SaveValues(ArrayList<String> arrayList1, ArrayList<String> arrayList2, String valueType, String timeStart, String timeStop) {
String filename = "File_" + valueType + "_" + timeStart + " bis " + timeStop;
FileOutputStream outputStream = null;
if(arrayList1.size() == 0)
return false;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < arrayList1.size(); i++) {
outputStream.write(arrayList1.get(i).getBytes());
outputStream.write("\n".getBytes());
outputStream.write(arrayList2.get(i).getBytes());
outputStream.write("\n".getBytes());
}
outputStream.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I also save the valuetype, timeStart and timeStop into a database to be able to find the files. My problem is, that somehow the table where I save these values got deleted, so I am not able to find the files in the app. I would like to find the files maybe on the phone or something. Actually, I just need the filenames to be able to open them in the app, because they contain data I need. So, where can I find these files?
I have tried searching in the phones files. The files, and all the other apps data, should be saved in Android/data/package-name but I can't find the package name in Android/data. I also tried to search for "File_" in the files, because that's what every one of my files start with. But no file gets found.

Save a File on a specific path

i have the current code:
public void crearArchivo(String nombre) {
archivo = new File(nombre.replaceAll("\\s", "") + ".txt");
if (!archivo.exists()) {
try {
archivo.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void crearCarpeta(String nombreCarpeta){
File directorio = new File(nombreCarpeta);
directorio.mkdir();
}
public void crearArchivoDatos(String nombreArchivo, ArrayList<String>datos) {
crearArchivo(nombreArchivo);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(archivo));
for (int i = 0; i < datos.size(); i++) {
bw.write(datos.get(i));
}
bw.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
the first method create a file only if it doesnt exist and the second one create a folder finally the third method save the data my problem is that i want to save some files on the folder i created first how can i set a path to save those file there, also i have the problem that this little program will execute at diferent computers so the path will change for any computer
You can get paths of folders on any computer using System.getProperty(...) - for example System.getProperty("user.home") gives you the current user directory (from which you can get to the desktop and other folders), and System.getProperty("user.dir") gives you the path of the folder from which your program is executed.
Creating or modifying files in Java can be done with the Java 8 NIO.2 methods.
Here is a link to the Oracle documentation : https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
For your question, you have to declare a relative path, so it will be independent of the computer it will be executed on, rather than an absolute path, which begin on the root of the filesystem.

Get the filename of the file from FileNotFoundException

I want to get the filename of the file that do not exist when a file exception occur in my java application so that i can give a short message to the user.
catch (FileNotFoundException e) {
/* what code to put here to get the filename of the file */
}
This should display the non-existing file path:
try {
//access file
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
Output, for creating a Scanner with new Scanner(new File("C:/filetest")):
C:\filetest (The system cannot find the file specified)
You cannot grap properly the filename unless you parse the stacktrace in your catch block.
You can either store the filename outside of the try block, i.e.:
String filename = ...
try {
// process file
} catch (FileNotFoundException e) {
String message = String.format("The file % could not be found.", filename);
// Show message to user
}
Or you can check whether the file exists before trying to access it:
File file = new File(filename);
if (!file.exists()) {
// Show error to user.
}

Filer always throws FilerException

Edit: I just found out that not a IOExcpetion but a FilerException is thrown. Therefore I changed that in the description and the title.
I'm working with Annotation Processing to generate some files for my java project. Now I always get an FilerException when the Annotation Processing tries to generate my files.
This is the way I create the files (GenClass and GenAnnotation are custom classes that abstract the generated classes. They weren't changed in about half a year so I'm sure the error isn't somewhere there. The way I write the files also didn't change in the last year.):
public static boolean generateJavaSourceFile(final ProcessingEnvironment processingEnv,
final GenClass element, final String fileName, final Class<?> generatorClass) {
boolean succeed = false;
Writer fw = null;
Filer f = processingEnv.getFiler();
// Mark the class as generated
GenAnnotation generatedAnnotation = getAnnotation(generatorClass);
element.pushImport(generatedAnnotation);
element.addAnnotation(generatedAnnotation);
try {
JavaFileObject jfo = f.createSourceFile(fileName, (Element[]) null);
// create new java source file
fw = jfo.openWriter();
// write the GenClass object into file
fw.write(element.toString());
succeed = true;
} catch (FilerException e) {
LOGGER.severe("Couldn't generate file (" + fileName + ")!");
processingEnv.getMessager().printMessage(Kind.ERROR,
"Could not create source file " + fileName
+ " because it already exists");
throw new RuntimeException(e.getMessage(), e);
} catch (IOException e) {
LOGGER.severe("Couldn't generate file (" + fileName + ")!");
throw new RuntimeException(e.getMessage(), e);
} finally {
if (fw != null) {
try {
fw.close(); // flush and close the stream
} catch (IOException e) {
LOGGER.severe("Couldn't close file [" + fileName + "]!");
}
}
}
LOGGER.fine(fileName + " written");
return succeed;
This is the message of the exception:
Source file already created: /path/to/the/file/to/create
I did change something on my processors, however the error only occurs for a certain type of files (Filters we use to filter data) and I didn't change anything on the processor that generates the filters. I added a new processor that works with a different annotation and those file are generated correctly.
Does anyone know what the cause of this error could be?
I had an error in another processor (that had nothing to do with the processor that generates the Filters) and that caused this error. Now that I fixed that error also this behavior stopped. I'm not really sure why this FilerException happened all the time, however it is gone now.

Unable to delete files using Java

I have written the following code to merge and delete the source files,but somehow the source files are not getting deleted.Can any one please throw some light on what i 'm missing here.
public void doDelete(List<String> dID)throws IOException {
String DID=null;
try{
for( ListIterator<String> iterator = dID.listIterator(); iterator.hasNext();)
{
DID= (String) iterator.next();
System.out.println("Deleting PDF" +DID);
File f =new File("E:\\TestFolder"+ "\\" +DID+".pdf");
if (!f.exists()) {
System.err.println("File " + f
+ " not present to begin with!");
return;
}
System.out.println(f.length());
System.out.println(f.getAbsolutePath());
boolean success = f.delete();
if (!success){
System.out.println("Deletion failed.");
}else{
System.out.println("File deleted."+DID);
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
TL;DR but file deletion failures is usually due to the file still being open. Especially as you are running it on Windows.
If you would like to get a reason for the delete failure you can use the Java 7 file API instead, it will give you the deletion failure reason as an exception.
java.nio.Files.delete(...)
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#delete(java.nio.file.Path)
In your createFileFromBlob method you are opening multiple FileOutputStreams (for each element of dID.listIterator()) but only closing the last one in your finally block. This will leave an open handle to all files other than the last, preventing them from being deleted as per Pulsar's answer.

Categories

Resources