filesharing from 2 computers. - java

Well, I have this program, the download option is working fine. I can access the other computer and download the file from it to my desktop, but the upload is a problem. When I choose the file, the program tries to get the file from the other computer and not mine so the path is wrong. Is there somehow I can use JFileChooser (as I do in download) and put in my computer name or IP address? Before I started to try the access to another computer I did make it work with JFilChooser, but the path messes it up now. Some tips or tricks?
public void upload(String username) throws RemoteException, NullPointerException{
try {
System.out.println(getProperty);
String lol = "/hei/hei.txt";
String ServerDirectory=("//" + "JOAKIM-PC"+ "/Users/Public/Server/");
byte[] filedata = cf.downloadFile2(getProperty + lol);
File file = new File(getProperty + lol);
BufferedOutputStream output = new BufferedOutputStream
(new FileOutputStream(ServerDirectory + file.getName()));
output.write(filedata,0,filedata.length);
output.flush();
output.close();
} catch(Exception e) {
System.err.println("FileServer exception: "+ e.getMessage());
e.printStackTrace();
}
}
public void download(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser("//" + "JOAKIM-PC" + "/Users/Joakim/Server/");
chooser.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return (f.isDirectory() && f.getName().equals("Server"));
}
});
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
File selectedFile = chooser.getSelectedFile();
String clientDirectory = getProperty + "/desktop/";
byte[] filedata = cf.downloadFile(selectedFile);
System.out.println("Byte[] fildata: " + selectedFile);
File file = new File(fileName);
System.out.println("fileName: " + fileName);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(clientDirectory + file.getName()));
output.write(filedata, 0, filedata.length);
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}

If I understood well, you want to use on your upload method this code:
JFileChooser chooser = new JFileChooser("./hei/");
int returnval = chooser.showOpenDialog(this);
String ServerDirectory=("//" + "JOAKIM-PC"+ "/Users/Public/Server/");
if(returnval == JFileChooser.APPROVE_OPTION){
File file = chooser.getSelectedFile();
try{
byte[] filedata = cf.downloadFile2(file.getAbsolutePath());
BufferedOutputStream output = new BufferedOutputStream
(new FileOutputStream(ServerDirectory + file.getName()));
output.write(filedata,0,filedata.length);
output.flush();
output.close();
}
catch(Exception e){
e.printStackTrace();
}
}
Is it right for you?

Related

Improper Resource Shutdown or Release

Description:
In the code below What am i doing wrong in the code below, in my code audit i got improper resource shutdown or release.
I tried taking out the close and flush from the code below
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
fos.flush();
fos.close();
Main code:
FileOutputStream fos=null;
try {
Hashtable hash = responseBlob.getAllAttachments();
Enumeration e = hash.elements();
while (e.hasMoreElements()) {
SBADataAttach tmpAttach = (SBADataAttach) e.nextElement();
String tag = tmpAttach.getTag();
byte[] data = tmpAttach.getData();
// encode compressed file
if (hasTag(tag))
mimeResponse.addPart(tag, Base64.encodeBytes(data)
.getBytes());
else
mimeResponse.addPart(tag, data);
try {
if (this.configData.getBlobPath() != null)
{
// save compressed file
String fileName = File.separatorChar + "tmp"
+ File.separatorChar + tag;
Log.theLogger.debug("XisServlet.process() ... "
+ "Save compressed file = " + fileName);
File someFile = new File(fileName);
fos = new FileOutputStream(
someFile);
fos.write(data);
fos.flush();
fos.close();
}
} catch (Exception zipe) {
Log.theLogger.error(zipe.getMessage(), zipe);
}
}
} catch (SBADataException sde) {
// cannot detach files from blob
Log.theLogger.error(sde.getMessage(), sde);
}
finally {
try {
if( fos!=null ) {
fos.close();
}
} catch(IOException e) {
Log.theLogger.error(e.getMessage(), e);
}
}
I don't get any error. But in the Appsec finding i getImproper Resource Shutdown or Release
try{
//open resources
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
}
catch(Exception e1){
//handle exception
}finally{
//close resources
fos.flush();
fos.close();
}
}

Unable to create a text file on sd card (external storage) even after providing run time read and write permissions

I have given Read and write external storage permissions in the AndroidManifest.xml file and also checking for the permissions during runtime. But still unable to create a text file on SD card
Code below:
try {
File dir = new File(getExternalStoragePath() + "/" + IMAGE_DIRECTORY_NAME);
String path;
if (!dir.exists())
dir.mkdirs();
path = dir.getAbsolutePath();
showMessage("path: " + path);
File myFile = new File(path + File.separator + "MyTextFile.txt");
// Adds a line to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(myFile, true /*append*/ ));
writer.write("This is a test file.");
writer.close();
Toast.makeText(processTrailerFragmentContext,
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(processTrailerFragmentContext, "Exception: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
/**
* Method will return the path of the sd card
* #return sd card path
*/
public String getExternalStoragePath() {
String internalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String[] paths = internalPath.split("/");
String parentPath = "/";
for (String s: paths) {
if (s.trim().length() > 0) {
parentPath = parentPath.concat(s);
break;
}
}
File parent = new File(parentPath);
if (parent.exists()) {
File[] files = parent.listFiles();
for (File file: files) {
String filePath = file.getAbsolutePath();
Log.d(PROCESS_TRAILER_TAG, filePath);
if (filePath.equals(internalPath)) {
continue;
} else if (filePath.toLowerCase().contains("sdcard")) {
return filePath;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
if (Environment.isExternalStorageRemovable(file)) {
return filePath;
}
} catch (RuntimeException e) {
Log.e(PROCESS_TRAILER_TAG, "RuntimeException: " + e);
}
}
}
}
return null;
}
Try this below snippet code:
File file = new File("/sdcard/textFile.txt");
FileOutputStream stream = null;
try {
stream = new FileOutputStream(file);
String uristr = "text files content";
stream.write(uristr.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Java - Setting Value in Properties File is Overwritting Previous Values

I have a class that manages all the settings with methods:
public class SettingsManager {
public String settingsFileName = Start.programName + ".settings";
public SettingsManager(String settingsFileName) {
this.settingsFileName = settingsFileName;
}
public void saveIntoNewSettings(String nameOfSetting, String settingValue) {
Properties programProperties = new Properties();
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(this.settingsFileName);
programProperties.setProperty(nameOfSetting, settingValue);
programProperties.store(outputStream, null);
outputStream.close();
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to save a setting into the file " + this.settingsFileName + ".");
}
}
public void saveSetting(String nameOfSetting, String settingValue) {
try {
InputStream inputStream = new FileInputStream(this.settingsFileName);
OutputStream outputStream = new FileOutputStream(this.settingsFileName);
Properties programProperties = new Properties();
programProperties.load(inputStream);
inputStream.close();
programProperties.setProperty(nameOfSetting, settingValue);
programProperties.store(outputStream, null);
outputStream.close();
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to load a setting from the file " + this.settingsFileName + ".");
}
}
public String loadSetting(String nameOfSetting) {
Properties programProperties = new Properties();
InputStream inputStream = null;
try {
inputStream = new FileInputStream(this.settingsFileName);
programProperties.load(inputStream);
inputStream.close();
return programProperties.getProperty(nameOfSetting);
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to load a setting from the file " + this.settingsFileName + ".");
}
return "";
}
public boolean settingsFileExists() {
File settingsFile = new File(settingsFileName);
if (settingsFile.exists() && !settingsFile.isDirectory()) {
return true;
}
else {
return false;
}
}
}
After creating an instance of this class named "mainSettings", I run these two lines of code in my main class:
mainSettings.saveSetting("hello1", "world1");
mainSettings.saveSetting("hello2", "world2");
In my settings file, all I see is this:
hello2=world2
For some reason every time I call the saveSetting method it gets rid of older values in the settings file. I thought that those values should be saved when I called "programProperties.load(inputStream);".
When you create the OutputStream the file is being truncated to 0 bytes. Infect you do not have any properties read. Try this:
public void saveSetting(String nameOfSetting, String settingValue) {
try {
InputStream inputStream = new FileInputStream(this.settingsFileName);
Properties programProperties = new Properties();
programProperties.load(inputStream);
inputStream.close();
OutputStream outputStream = new FileOutputStream(this.settingsFileName);
programProperties.setProperty(nameOfSetting, settingValue);
programProperties.store(outputStream, null);
outputStream.close();
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to load a setting from the file " + this.settingsFileName + ".");
}
}
Should solve your issue.

How to close and delete file in Java

I have written code that should be saved file in the local directory, create zip of that file, send email and delete both files (original and zip), So this is my code:
Method wich send email
public void sendEmail(Properties emailProperties, InputStream inputStream, HttpServletRequest request) throws UnsupportedEncodingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
try {
mimeMessageHelper.setFrom(from, personal);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage());
throw new SequelException(e.getMessage());
}
mimeMessageHelper.setTo(recipients);
mimeMessageHelper.setSubject(emailProperties.getProperty(PARAM_TITLE));
String message = emailProperties.getProperty(PARAM_EMLMSG);
mimeMessageHelper.setText(message);
InputStreamSource inputStreamSource = null;
if (inputStream != null) {
inputStreamSource = new ByteArrayResource(IOUtils.toByteArray(inputStream));
}
String compressType = COMPRESS_TYPE_ZIP;
String fileName = getAttachFilenameExtension(object, format);
Path filePath = Paths.get(StrUtils.getProperty("temp.email.files.path") + "\\" + fileName);
tempFile = saveTempFile(inputStreamSource.getInputStream(), filePath);
if (tempFile.length() > 0) {
inputStreamSource = compressFile(tempFile, filePath.toString(), compressType);
fileName = StringUtils.substring(fileName, 0, StringUtils.lastIndexOf(fileName, ".")+1) + compressType;
}
mimeMessageHelper.addAttachment(fileName, inputStreamSource);
mailSender.send(mimeMessage);
} catch (MessagingException | IOException e) {
LOGGER.error(e.getMessage());
throw new SequelException(e.getMessage());
} finally {
List<File> files = (List<File>) FileUtils.listFiles(tempFile.getParentFile(), new WildcardFileFilter(
FilenameUtils.removeExtension(tempFile.getName()) + "*"), null);
for (File file : files) {
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
}
}
Save file in directory:
private File saveTempFile(InputStream inputStream, Path filePath) throws IOException {
Files.deleteIfExists(filePath);
Files.copy(inputStream, filePath);
return new File(filePath.toString());
}
Compress file:
private InputStreamSource compressFile(File file, String filePath, String compressType) throws IOException {
InputStream is = ZipFile(file, filePath);
InputStreamSource inputStreamSource = new ByteArrayResource(IOUtils.toByteArray(is));
return inputStreamSource;
}
public InputStream ZipFile(File file, String filePath) {
String zipArchiveFileName = StringUtils.substring(filePath, 0, filePath.lastIndexOf(".") + 1) + COMPRESS_TYPE_ZIP;
try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File(zipArchiveFileName));) {
ZipArchiveEntry entry = new ZipArchiveEntry(StringUtils.overlay(file.getName(), "",
StringUtils.lastIndexOf(file.getName(), "_"), StringUtils.lastIndexOf(file.getName(), ".")));
zipOutput.putArchiveEntry(entry);
try (FileInputStream in = new FileInputStream(file);) {
byte[] b = new byte[1024];
int count = 0;
while ((count = in.read(b)) > 0) {
zipOutput.write(b, 0, count);
}
zipOutput.closeArchiveEntry();
}
InputStream is = new FileInputStream(zipArchiveFileName);
return is;
} catch (IOException e) {
LOGGER.error("An error occurred while trying to compress file to zip", e);
throw new SequelException(e.getMessage());
}
}
So the problem is when I try to delete files but zip file does not delete.
I am using Apache commons compress for zipping.
Can you help what's wrong?
For me this code is working perfectly. After compressing you may be trying to delete it without the extension(for eg .7z here).
public static void main(String[] args) {
File file = new File("C:\\Users\\kh1784\\Desktop\\Remote.7z");
file.delete();
if(!file.exists())
System.out.println("Sucessfully deleted the file");
}
Output:-
Sucessfully deleted the file

in primefaces 3 and jsf i upload the file but in destination place the image is not show

i used simple mode, glassfish 3.0 and primefaces 3.0
Backing Bean
private UploadedFile file;
private String destination="D:\temp\";
public void upload(FleUploadEvent event) {
System.out.println("upload");
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("uploaf finished");
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination + fileName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
this is my jsf page
In your example "D:\tmp\" is followed by the full filename of the uploaded file, i.e. "C:\Users\admin\Desktop\ulcerimage.jpg".
This is incorrect and leads to the error.
All what you need is to process uploaded filename: extract actual name without path information.
You can use for example the following:
if (fileName.indexOf("/")>0){
fileName = fileName.substring(fileName.lastIndexOf("/"));
}
OutputStream out = new FileOutputStream(new File(destination + fileName));
in copyFile method.

Categories