How to save an PNG via code in a Runnable JAR file? - java

I'm having trouble fixing this issue,
I have created a Client\Server side application and created a Method where a user can
"Send" a PNG file from his side to Server side, then the Server side "Creates" and saves the image in a Package that only contains pictures.
When i run this Method of sending a Picture from Client side to Server side via Eclipse IDE
it works as expected, but when exporting Client/Server side into Runnable JAR files, i get the next error:
Java
private static void getImg(MyFile msg) {
int fileSize =msg.getSize();
System.out.println("length "+ fileSize);
try {
File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
FileOutputStream fileOut;
fileOut = new FileOutputStream(newFile);
BufferedOutputStream bufferOut = new BufferedOutputStream(fileOut);
try {
bufferOut.write(msg.getMybytearray(), 0, msg.getSize());
fileOut.flush();
bufferOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I get the follow error :
java.io.FileNotFoundException: java.io.FileNotFoundException: C:\Users\Ilya\Desktop\src\GuiServerScreens\test.png (The system cannot
find the path specified)
It seems that using File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
Does not provide the wanted result

I think you are mixing what your directories look like in netbeans with what's available on the server. Save to an external directory instead, not to your src directory.

Related

After File compression I lost the Filename extension

I am trying to compress my file using the ZipOutPutStream. I tried below code and got the compressed folder with the file. But when I am extracting the folder using 7Zip, the fileName extension is missing.
Also I am unable to extract the folder by normal Extract option provided in Windows.
Below is the code I tried Using Java -8
public void compress(String compressed , String raw) {
Path pCompressed = null;
try {
pCompressed = Files.createFile(Paths.get(compressed));
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(pCompressed))) {
Path pRaw = Paths.get(raw);
Files.walk(pRaw).filter(path -> !Files.isDirectory(path)).forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pRaw.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
logger.error("Exception while copying file to compressed Directory: "+e);
}
});
}
catch(IOException ioe) {
logger.error("Exception while compressing the output file: "+ioe);
}
}
catch (IOException e1) {
logger.error("Exception While Path initialization for compressing the file");
}
}
Expecting : After Extraction someFolder/MyFile.csv
I've just tried this code and when I provided it with compressed = "out.zip" and raw = "testdir", it worked fine for me. It produced a zip file containing the contents of testdir. I was then able to extract this with 7Zip and the built in Windows extraction and the files were all present and correct.
My guess is that you have not specified the .zip extension for the output file or that Windows is hiding the extension in the folder view. (I think it does this by default.)

Android Studio write to .properties file

I followed Where to put own properties file in an android project created with Android Studio? and I got an InputStream which reads from my .properties file successfully. However, I can't write to that .properties file, as there is no similar method to getBaseContext().getAssets().open ("app.properties") which returns an OutputStream. I have also read Java Properties File appending new values but this didn't seem to help me, my guess is my file name for the file writer is wrong but I also tried "assets\userInfo.properties" which also doesn't work.
My .properties file is in src\main\assets\userInfo.properties
Properties props = new Properties();
InputStream inputStream = null;
try{
inputStream = getBaseContext().getAssets().open("userInfo.properties");
props.load(inputStream);
props.put("name", "smith");
FileOutputStream output = new FileOutputStream("userInfo.properties"); //this line throws error
props.store(output, "This is overwrite file");
String name = props.getProperty("name");
Log.d(TAG, "onCreate: PROPERTIES TEST NAME CHANGE: " + name);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Current code throws this error:
java.io.FileNotFoundException: userInfo.properties (Read-only file system)
You can't write to the assets folder, as it is inside the APK which is read-only.
Use internal or external storage instead
You can't write to the assets folder. If you want to update your properties file, you'll have to put them some place else. If you want the initial version in the assets or raw folder, just copy it to the default files dir when the app is first used, then read from/write to it there.

java.io.FileNotFoundException when creating FileInputStream

Getting an error when trying to open a FileInputStream to load Map from file with .ser extension.
Constructor where I create new File and invoke method that loads map from file:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("database.ser"); // oddly this does not create a file if one does not exist
loadDB();
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn);
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I've tried to create file manually and put it in same package with class, but it does not help. What's going on?!
Thank You!
You provide a relative path for the file. That means program will look for the file relative to the working directory.
Depending on how you run the program it will be the directory you run it from (if run from Shell/Cmd) or whatever is configured in the project settings (if run from the IDE). For the latter, it depends on the IDE but usually it's the project root directory.
More info on working directory: https://en.wikipedia.org/wiki/Working_directory
More info on relative path: https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths
Regarding creation of the file, it would create non-existing file if you were to write to it. When you read it, it expects it to exist. That means you have to create empty file (if one does not exist) before reading or simply treat exception as empty content.
The path to the file you have given might be wrong for IDE it can take relative path but from the command line, it will take the absolute path.

Copy file from Android to Windows

I wrote a small app, which creats a XML file on my Android device. No I try to copy it from my phone to my Windows PC. In Windows Explorer I can't see this file specific file, on my phone I can see this file with various file explorers. When I reboot my phone, the file appears in Windows Explorer, but I can't copy it to my desktop.
Here is my code which creates my file:
String filename = "myfile.xml";
String dir = Environment.getExternalStorageDirectory().getPath()+"/"+c.getResources().getString(R.string.app_name);
createDir(dir);
File file = new File(dir,filename);
FileWriter out=null;
try {
String xml = createXml();
try {
out = new FileWriter(file);
out.write(xml);
out.close();
} catch (Exception e) {
out.close();
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
My guess is, this code doesn't free the file handle so Androids MTP cannot access this file. This would also explain, why the file is shown and could be deleted (but not able to be transfered to my PC) after rebooting my phone.
Any suggestions what goes wrong?
I think you should refresh the media scanner for that file
sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded))
);

Java FTP commons-net error downloading files

I'm using apache commons.net to access an ftp site which is the directory is in unix:
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
I'm looping thru a list with the names of the filenames I want to download on a specific ftp site
String ftpPath = "/home/user1/input/";
FileOutputStream fos = null;
File file;
try {
for (int i = 0; i < fileList.size(); i++) {
file = new File(ftpPath+fileList.get(i).toString());
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(file));
boolean download = ftpClient.retrieveFile("c:/test/downloadedFile.csv", outputStream1);
outputStream1.close();
if (download) {
System.out.println("File downloaded successfully !");
} else {
System.out.println("Error in downloading file ! " + downloadFile);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But once I try to start to download the files I get this error althougth checking the ftp site the file exists under /home/user1/input/TejasSDH_PM_AU_09_07_2014_09_00.csv -rw-r--r--:
java.io.FileNotFoundException: \home\user1\input\TejasSDH_PM_AU_09_07_2014_09_00.csv (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at com.syntronic.client.FTPDataExtract$1.downloadTejasFiles(FTPDataExtract.java:255)
at com.syntronic.client.FTPDataExtract$1.run(FTPDataExtract.java:133)
I'm thinking as the ftp site I'm connecting, the path dir is in unix home/user1/input and java is converting all the "/" to "\". Anyone has an idea on what the error in eclipse means or is something wrong with my code? thank you
You seem to be switching things around.
You are opening a file outputstream to \home\user1\input\TejasSDH_PM_AU_09_07_2014_09_00.csv and you seem to be on windows so it won't work.
You have the local path where the ftp path should go and the other way around.
Please read your errors more carefully, I'm willing to bet that line 255 in FTPDataExtract.java is:
fos = new FileOutputStream(downloadFile);
Which should alert you to the fact that it's not actually an ftp problem.
for (int i = 0; i < fileList.size(); i++) {
OutputStream output;
output = new FileOutputStream("C:/test/" + fileList.get(i).toString());
ftpClient.retrieveFile(ftpPath + fileList.get(i).toString(), output);
output.close();
}
I wrongfully switch the remote and local path, switching it properly will run the program smoothly.

Categories

Resources