I found something wrong when I write the Properties file by using FileOutputStream.
public synchronized static void setProperties(String file,String Properties,String value)
{
try {
FileInputStream is = new FileInputStream(file);
Properties proper = new Properties();
proper.load(is);
proper.setProperty(Properties.toUpperCase(), value);
is.close();
FileOutputStream os = new FileOutputStream(file);
proper.store(os,"Update the file:"+Properties);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Look at the two lines below:
FileOutputStream os = new FileOutputStream(file);
proper.store(os,"Update the file:"+Properties);
When the first line executed, the file will be empty, until the second line execute finished. Now, I assume the second line will execute within 3 seconds. During this period, the program crashed or another reason lead to the file to be unsuccessfully written. I will get an empty Properties file when I'm running my program next time. Anyone can tell me how to prevent this kind of situation to occur?
I changed my program like below, Seems it more better than before. At least I won't get a empty properties file, Thanks all guys.
public synchronized static void setProperties(String file,String Properties,String value)
{
try {
FileInputStream is = new FileInputStream(file);
Properties proper = new Properties();
proper.load(is);
proper.setProperty(Properties.toUpperCase(), value);
is.close();
proper.store(new FileOutputStream(file+".tmp"),"Update the file:"+Properties); //Prevent empty file
File old = new File(file);
File tmp = new File(file+".tmp");
if(tmp.exists() && tmp.length()>0)
{
old.renameTo(new File(file+".old"));
tmp.renameTo(new File(file));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
Currently I am shifted my server to linux from windows and I am facing some problem in my java webservice. In that I am creating a file in windows D drive. now I want to create that on linux server too. but I dont know how to give path and how to create (since it don't have drives as windows). so need some help for this. I am posting my java code below.
private static void receiveImg(String pic_bitmap) {
FileOutputStream fos;
try {
fos = new FileOutputStream("D:\\AllImages\\ProfilePic\\Test.png");
byte byteArray[] = Base64.decodeBase64(pic_bitmap);
fos.write(byteArray);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks for any help.
This should work. See below for more considerations
private static void receiveImg(String pic_bitmap) {
FileOutputStream fos;
try {
fos = new FileOutputStream("/tmp/test.png");
byte byteArray[] = Base64.decodeBase64(pic_bitmap);
fos.write(byteArray);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Note that you need to know the structure of the linux server to save it in a more suited place. If you can ssh onto the server you can run 'ls /' command to see the root folder structure. If you are not deploying the code yourself you may need a DevOps person to help you understand the folder structure on the destination server where you are deploying the code.
this could help you. It does not save an image, but that should not matter.
public void saveImage(String filename) { // filename ( path: linux ): /directory/filename
if(filename!=null){
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject('objectToWrite');
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}else{
System.out.println("NullPointerException");
}
}
This question already has answers here:
java.io.FileNotFoundException when creating FileInputStream
(2 answers)
Closed 6 years ago.
For my application I want to use a Map to act as a database. To save and load a map, I am writing/reading it to/from database.ser using this 2 methods:
private synchronized void saveDB() {
try {
fileOut = new FileOutputStream(db);
out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
fileOut.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to load into Map when application starts, so I invoke method in constructor like this:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("C:/Users/eduar/git/Multy-Threaded-Bank-System/Bank-Services/database.ser");
// also, any suggestions how can I make path to a file more flexible in case I want to run Server side of an app on different machine?
if (!db.exists()) {
try {
db.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
loadDB(); // loads database when server start
}
I am aware of what causing an error, but I don't know what should I change in my design to avoid ObjectInputStream constructor receiving empty stream!
Any suggestions on what I can do differently?
Edit: I want to note that in fresh application run database.ser is empty since there was no entries made into Map yet.
Thank You!
First why the EOFExcpetion occur?
There are no contents in file or file is empty and you tried to read file.
You can avoid the EOFException for an empty file by checking file content length if it is less than or equal to zero means file is empty. another way to check if file is empty
Some code change and it worked for me.
#SuppressWarnings("unchecked")
private void loadDB() {
try {
if (db.length() <= 0) {
// if statement evaluates to true even if file doesn't exists
saveDB(); // save to a file an empty map
// if file doesn't exist, it creates a new one
// call loadDB inside constructor
}
FileInputStream fileIn = new FileInputStream(db);
ObjectInputStream in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
in.readObject();
in.close();
fileIn.close();
System.out.println(accounts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Get rid of the file.exists()/file.createNewFile() crap. All it is doing for you is masking the original FileNotFoundException problem, and turning into a thoroughly predictable EOFException because of trying to construct an ObjectInputStream around an empty stream. Handle the original problem. Don't just move it, or turn it into something else.
I have a pretty weird problem. I wanted to write something (actually a String) to a file. I converted it into a byte array as usual, wrote that into the file and... there is only something written like: [B#42928da8. No matter what i write, how big that string is, or else, i don't get something much different. I'm thinking that that is an address to the array but how did it get there?
The function which is called when the "save" button is pressed.
public void saveNote(View view){
String FILENAME;
String content;
FILENAME = editText_name.getText().toString();
content = editText_note.getText().toString();
if (FILENAME.equals("LISTOFALLNOTES") || FILENAME.equals("TMP")){
if(requestdecision(getString(R.string.note_warning)))
{
}
else
return;
}
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showmessage("Fehler beim Erstellen der Datei");
}
try {
fos.write(content.getBytes());
fos.close();
showmessage("Erfolgreich gespeichert!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showmessage("Fehler beim Schreiben");
}
}
showmessage() is only a function which shows a simple info dialog.
I thank you for your advice.
EDIT: I just found out that if you reopen the notice/file the output changes. So I posted the reading function(s) here:
public void openNote(View view){
String FileName=editText_name.getText().toString();
if (FileName.equals("LISTOFALLNOTES") || FileName.equals("TMP") || FileName.equals("MAIN_DATA")){
if(requestdecision(getString(R.string.note_warning)))
{}
else
return;
}
editText_note.setText(readNote(FileName).toString());
}
public String readNote(String name){
File file = new File(this.getFilesDir(), name);
int length = (int) file.length();
String contents;
byte[] bytes = new byte[length];
FileInputStream in = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
showmessage("Datei nicht gefunden");
e.printStackTrace();
contents = "";
}
try {
in.read(bytes);
in.close();
contents=bytes.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
showmessage("Konnte nicht lesen");
e.printStackTrace();
contents = "";
}
}
Weird is also why that changes. Doesn't that somehow mean that the file is saved during the reading process?
Edit2: I just discovered that the file itself(read with a root filebrowser) is written normally so the problem has to be in the reading process.
I've had a similar issue like this before. What fixed it for me was not directly calling the content.getBytes() directly into the into the write method, but first making sure it's labeled as a byte array and then writing through the FileOutputStream.
String n_content = (String)content;
byte[] bContent = n_content.getBytes;
fos.write(bContent);
If this ceases to work I believe your openFileOutput() isn't returning a proper FileOutputStream instance.
This question already has answers here:
How to prevent InputStream.readObject() from throwing EOFException?
(3 answers)
Closed 9 years ago.
I can't seem to find a way to make readObject() transfer it's contents to an object variable. When I step through the Load function I get to "temp = (HashMap) ois.readObject();" Before this line is executed I am able to see the HashMap's data that I've written with oos in the expressions window of Eclipse so I know the data is there, however when this line executes I'm jumped to the IOException catch with an EOF. From what I've read this is expected, but I have not found a way to catch the EOF (loops with available() and readObjectInt() did not work). I'm running this on an Android emulator. Any suggestions would be appreciated.
public void Save(Pottylog data)
{
try
{
FileOutputStream fos = openFileOutput("Plog", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data.get());
oos.close();
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (java.io.IOException e)
{
e.printStackTrace();
}
}
public HashMap<String, Integer> Load()
{
HashMap<String, Integer> temp = null;
try
{
FileInputStream fis = openFileInput("Plog");
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (HashMap<String, Integer>) ois.readObject();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return temp;
}
EOFException means you have reached the end of the stream. I don't know what you think you're seeing in the debugger, but there is no object there in the stream to be read. catch(EOFException exc) does work; at this point you should close the stream and exit the reading loop. Don't misuse available() as an end of stream test: that's not what it's for.
i write ArrayLists into a file. I read it with FileInputStream. But always just the "first" ArrayList is appears by reading. I tried it with readInt() / wirteInt(), and loops, but there were always thrown exceptions, by calling readInt() --> EOF
I want to read all ArrayList from this File into an ArrayList. My application needs to be persistent, so i serialized the ArrayLists.
write into file:
try {
FileOutputStream fos = new FileOutputStream(_cache, true);
ObjectOutputStream os = new ObjectOutputStream(fos);
// os.writeInt(newValueList.size()); // Save size first
os.writeObject(newValueList);
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
read from file:
List cachedValueList = new ArrayList<String>();
ObjectInputStream o = new ObjectInputStream(new FileInputStream("caching.io"));
// int count = o.readInt(); // Get the number of regions
try {
cachedValueList.add(o.readObject());
} catch (EOFException e) {
o.close();
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you are writing the same list many times, it will only write the list once. After that it will use the same reference but the contents will be the same (this is true of any object)
If you call reset() between writeObject() it will send a fresh copy of the list each time.