How to create file on linux server using java - java

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");
}
}

Related

Extracting RAR with JunRAR [duplicate]

I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}

Workaround java.io.EOFException cause by ObjectInputStream [duplicate]

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.

How the FileOutputStream write properties file don't lost information

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();
}
}

How save a string to a file in Android to be able to read it later?

Im trying to implement the section "Using the Internal Storage" in http://developer.android.com/guide/topics/data/data-storage.html
I think I did the first part correctly, saving string to a file, but how do I read the string later?
Her is what my code looks like:
String FILEPROFILE = "profileinfo";
FileOutputStream fos = null;
BufferedInputStream fis = null;
OutputStream out = null;
try {
fos = openFileOutput(FILEPROFILE, Context.MODE_PRIVATE);
fos.write(profile.toString().getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis = new BufferedInputStream(new FileInputStream(FILEPROFILE));
Log.d("UsersThoughts", "BufferedInputStream is " + fis.read());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT:
I change it to this:
try {
fis = openFileInput(FILEPROFILE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("UsersThoughts", "This blah object read " + fis.read());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("UsersThoughts", "This blah object trying to read: " + e.toString());
}
try{
Log.d("UsersThoughts", "This blah object toString " + fis.toString());
} catch (Exception e)
{
e.printStackTrace();
Log.e("UsersThoughts", "This blah object trying to make string: " + e.toString());
}
The output in the logcat looks like this:
11-15 18:41:34.862: D/UsersThoughts(7777): This blah object read123
11-15 18:41:34.862: D/UsersThoughts(7777): This blah object toString java.io.FileInputStream#46356128
Looks like it's reading the files as bites....how do I get the text back that I copied?
Follow the answer i gave here to store a String to a file in Android: Should I store data in sqlite in case user is offline?
I'm quoting this from the same source you've cited:
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
Read bytes from the file with read().
Then close the stream with close().
EDIT: For example,
FileInputStream fis = openFileInput("FILENAME");
BufferedInputStream blah = new BufferedInputStream(fis);
Then do whatever you were doing earlier with this blah object.

Read many ArrayList Objects out of File with ObjectInputStream?

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.

Categories