I'm creating simple object serialization, and creation of BufferedOutputStream is raising an exception AccessDeniedException. Here is the code:
Path filePath = Paths.get("c:\\temp\\");
File xmlFile = new File("c:\\temp\\");
boolean success = xmlFile.mkdirs();
if (!success && ! xmlFile.exists() ) {
// Directory creation failed
System.out.println("Failed to create a file: " + filePath);
}
try (
ObjectOutputStream objectOut = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(filePath, StandardOpenOption.WRITE)))){
// Write three objects to the fi le
objectOut.writeObject(solarSystem); // Write object
System.out.println("Serialized: " + solarSystem);
} catch(IOException e) {
e.printStackTrace();
}
But directory is empty and if it doesn't not exist, it's created...
I'll repeat my comment here: you seem to try to write to a directory not to a file. Try changing filePath to a file instead.
Related
So i am getting back into writing Java after 4 years so please forgive any "rookie" mistakes.
I need to have a properties file where i can store some simple data for my application. The app data itself won't reside here but i will be storing info such as the file path to the last used data store, other settings, etc.
I managed to connect to the properties file which exists inside the same package as the class file attempting to connect to it and i can read the file but i am having trouble writing back to the file. I am pretty sure that my code works (at least it's not throwing any errors) but the change isn't reflected in the file itself after the app is run in Netbeans.
In the above image you can see the mainProperties.properties file in question and the class attempting to call it (prefManagement.java). So with that in mind here is my code to load the file:
Properties mainFile = new Properties();
try {
mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));
} catch (IOException a) {
System.out.println("Couldn't find/load file!");
}
This works and i can check and confirm the one existing key (defaultXMLPath).
My code to add to this file is:
String confirmKey = "defaultXMLPath2";
String propKey = mainFile.getProperty(confirmKey);
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
try{
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
mainFile.store(fos, "testtest3");
fos.flush();
}catch(FileNotFoundException e ){
System.out.println("Couldn't find/load file3!");
}catch(IOException b){
System.out.println("Couldn't find/load file4!");
}
} else {
// Throw error saying key already exists
System.out.println("Key " + confirmKey + " already exists.");
}
As i mentioned above, everything runs without any errors and i can play around with trying to add the existing key and it throws the expected error. But when trying to add a new key/value pair it doesn't show up in the properties file afterwords. Why?
You should not be trying to write to "files" that exist inside of the jar file. Actually, technically, jar files don't hold files but rather they hold "resources", and for practical purposes, they are read-only. If you need to read and write to a properties file, it should be outside of the jar.
Your code writes to a local file mainProperties.properties the properties.
After you run your part of code, there you will find that a file mainProperties.properties has been created locally.
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
Could order not to confuse the two files you specify the local file to another name. e.g. mainAppProp.properties .
Read the complete contents of the resource mainProperties.properties.
Write all the necessary properties to the local file mainAppProp.properties.
FileOutputStream fos = new FileOutputStream("mainAppProp.properties");
switch if file exists to your local file , if not create the file mainAppProp.properties and write all properties to it.
Test if file mainAppProp.properties exists locally.
Read the properties into a new "probs" variable.
Use only this file from now on.
Under no circumstances you can write the properties back into the .jar file.
Test it like
[...]
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
[...]
Reader reader = null;
try
{
reader = new FileReader( "mainAppProp.properties" );
Properties prop2 = new Properties();
prop2.load( reader );
prop2.list( System.out );
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
if (reader != null) {
reader.close();
}
}
}
[...]
}
output : with prop2.list( System.out );
-- listing properties --
defaultXMLPath2=testtest
content of the file mainAppProp.properties
#testtest3
#Mon Jul 14 14:33:20 BRT 2014
defaultXMLPath2=testtest
Challenge:
Read the Property file location in jar file
Read the Property file
Write the variable as system variables
public static void loadJarCongFile(Class Utilclass )
{
try{
String path= Utilclass.getResource("").getPath();
path=path.substring(6,path.length()-1);
path=path.split("!")[0];
System.out.println(path);
JarFile jarFile = new JarFile(path);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (entry.getName().contains(".properties")) {
System.out.println("Jar File Property File: " + entry.getName());
JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
InputStream input = jarFile.getInputStream(fileEntry);
setSystemvariable(input);
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Jar file"+line);
}
reader.close();
}
}
}
catch (Exception e)
{
System.out.println("Jar file reading Error");
}
}
public static void setSystemvariable(InputStream input)
{
Properties tmp1 = new Properties();
try {
tmp1.load(input);
for (Object element : tmp1.keySet()) {
System.setProperty(element.toString().trim(),
tmp1.getProperty(element.toString().trim()).trim());
}
} catch (IOException e) {
System.out.println("setSystemvariable method failure");
}
}
Im trying to create a file if it doesnt exist, if it does exist append to it.
Is this the best way to do it? Im not sure having two try catches inside one method is good personally?
public static void main(String [] args)
{
String fileLocation = "/temp/";
String name = "Bob";
String timeStamp = "1988-03-15";
Path path = Paths.get(fileLocation+ "info.log");
if(!Files.exists(path)){
try {
Files.createFile(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
SimpleDateFormat tTimeFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
writer.write(tTimeFormatter.format(System.currentTimeMillis()) + " name: " + name + " Timestamp: "+ timeStamp);
writer.newLine();
} catch (IOException e) {
System.out.print(e.getStackTrace());
}
}
You can write to file with StandardOpenOptions: CREATE and APPEND.
Files.write(Paths.get(""), new byte[] {}, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
CREATE - means if file doesn't exists it creates new one otherwise get existing.
APPEND - means append new data to existing content in file.
So, you can do all your operations with a single line.
The File.createNewFile() method creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. This methods return a true value if the file is created successfully and false if the file already exists or the operation failed.
if (myFile.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
Try using the printWriter class like this
java.io.PrintWriter p = new java.io.PrintWriter(yourFileHere);
// You can use println to print a new line if it allready exists
p.println(yourTextHere);
// Or append to the end of the file
p.append("TEXT HERE!!!!")
I have this method, supposed to write an arrayList to a file:
private ArrayList<String> readFromFile() {
String ret = "";
ArrayList<String> list = new ArrayList<String>();
try {
InputStream inputStream = openFileInput("jokesBody.bjk");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
list.add(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
System.out.println("DA CRAZY FILE: " + ret);
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return list;
}
The problem with it is that it writes the values like [item1, item2, item3] and later when I need to load a the values back to a listArray it's loading the whole line at index 0. Now I have found the corerct way to write and read the arrayList, but I'm having troubles accessing teh file.
Here is the code I tried:
private void writeToFile(ArrayList<String> list) {
try {
FileOutputStream fos = new FileOutputStream("jokesBody.bjk");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list); // write MenuArray to ObjectOutputStream
oos.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
But it throws the following exception:
02-12 09:21:10.227: E/Exception(2445): File write failed: java.io.FileNotFoundException: /jokesBody.bjk: open failed: EROFS (Read-only file system)
Where is the mistake, where is the default app file location? I know that I'm missing something small, but as an android beginner, I'm not able to spot it.
Isn't this:
java.io.FileNotFoundException: /jokesBody.bjk: open failed: EROFS (Read-only file system)
the issue ? You're writing to a non-writeable area. Change where you're writing to (perhaps creating a temporary file would be a simple first step - I'm not familiar with Android but I assume this is possible)
Your file seems to be read only. You cannot write to a read only file!!!
I don't think you're actually saving the file where you think you are. Look at this tutorial on writing a file to external storage. A few things:
(1) You need to request permission in your manifest to write to external storage. If not you will end up with a read only situation.
(2) You need to get the external storage directory in your code before you write to it. This should be preceeded with a general check as to whether your file directory is writeable in the first place:
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
You can then create a specific directory for the files you want to store and store them in that location so you can find them later. For example:
public File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
You can then write content to the file that is returned
When you are developing for Android, you must get the OutputStream from the Context:
fos = context.openFileOutput("jokesBody.bjk", Context.MODE_PRIVATE);
An explanation about how to work with files on Android is here: Saving Files
So, here is the code that I have:
try
{
PlayerSave save = new PlayerSave(this);
save.playerLooks = look;
File test = new File("C:/cache/" + playerName + ".tmp");
test.createNewFile();
FileOutputStream f_out = new
FileOutputStream("C:/cache/" + playerName + ".tmp");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject (save);
obj_out.close();
f_out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Upon execution, I get the following error:
java.io.FileNotFoundException: C:\cache\Bobdole.tmp (The system cannot find the path specified)
I have also tried using this code:
try
{
PlayerSave save = new PlayerSave(this);
save.playerLooks = look;
// File test = new File("C:/cache/" + playerName + ".tmp");
// test.createNewFile();
FileOutputStream f_out = new
FileOutputStream("C:/cache/" + playerName + ".tmp");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject (save);
obj_out.close();
f_out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
However, it produces the same error. I am confused as to why this is not working, as everything seems to be right. If you guys can figure out the problem that would be so helpful.
Thanks!!
That's telling you that the directory C:\cache does not exist. The directory must exist in order for you to be able to write files to it. You can either create it manually, or with something like:
File directory = new File("C:\\cache");
directory.mkdir();
The program can't find your folder.
I am trying to create a file inside a directory using the following code:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("themes", Context.MODE_WORLD_WRITEABLE);
Log.d("Create File", "Directory path"+directory.getAbsolutePath());
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
Log.d("Create File", "File exists?"+new_file.exists());
When I check the file system of emulator from eclipse DDMS, I can see a directory "app_themes" created. But inside that I cannot see the "new_file.png" . Log says that new_file does not exist. Can someone please let me know what the issue is?
Regards,
Anees
Try this,
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
try
{
new_file.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Create File", "File exists?"+new_file.exists());
But be sure,
public boolean createNewFile ()
Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).
Creating a File instance doesn't necessarily mean that file exists. You have to write something into the file to create it physically.
File directory = ...
File file = new File(directory, "new_file.png");
Log.d("Create File", "File exists? " + file.exists()); // false
byte[] content = ...
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content);
out.flush(); // will create the file physically.
} catch (IOException e) {
Log.w("Create File", "Failed to write into " + file.getName());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
Or, if you want to create an empty file, you could just call
file.createNewFile();
Creating a File object doesn't mean the file will be created. You could call new_file.createNewFile() if you wanted to create an empty file. Or you could write something to it.