i'm attempting to fetch a list of files from server and copy them to directory .
and this error prompts.
java.rmi.NoSuchObjectException: no such object in table
at javafxhomeui_1.HomeUI_2Controller.writeFileToLocalHDD(HomeUI_2Controller.java:427)
at javafxhomeui_1.HomeUI_2Controller.initialize(HomeUI_2Controller.java:312)
HomeUI_2Controller.java
RemoteInputStream ris= null;
File[] iconlist=null;
try {
File appicon=new File("D:\\SERVER\\Server Content\\Apps\\icons");
iconlist=appicon.listFiles();
for (File file1 : iconlist) {
ris = downloadcontroller.getFile(file1.getAbsolutePath());
System.out.println(file1.getName());
}
} catch (Exception ex) {
Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
}
try {
for (File file1 : iconlist) {
//System.out.println("D:\\client\\Temp\\"+file1.getName());
/*line:312 */ writeFileToLocalHDD(ris,"D:\\client\\Temp\\"+file1.getName());
}
} catch (Exception ex) {
Logger.getLogger(HomeUI_2Controller.class.getName()).log(Level.SEVERE, null, ex);
}
public static void writeFileToLocalHDD(RemoteInputStream inFile, String fileLocation) throws IOException {
// wrap RemoteInputStream as InputStream (all compression issues are dealt
// with in the wrapper code)
/* line:427*/ InputStream istream = RemoteInputStreamClient.wrap(inFile);
BufferedInputStream bis = new BufferedInputStream(istream);
//downloaded file...
File file = new File(fileLocation);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
FileChannel channel = fileOutputStream.getChannel();
byte b[] = new byte[1024];
long startTime = System.currentTimeMillis();
while (bis.available()>0) {
bis.read(b);
System.out.println((System.currentTimeMillis() - startTime)/1000);
ByteBuffer buffer = ByteBuffer.wrap(b);
channel.write(buffer);
}
bis.close();
fileOutputStream.flush();
channel.close();
fileOutputStream.close();
}
////////////////////////////////////////////////
public RemoteInputStream getFile(String fileName) throws IOException {
// create a RemoteStreamServer (note the finally block which only releases
// the RMI resources if the method fails before returning.)
//read data
RemoteInputStreamServer istream = null;
try {
File file = new File(fileName);
System.out.println(file.exists());
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInputStream);
istream = new SimpleRemoteInputStream(bufferedInputStream);
// export the final stream for returning to the client
//send data
RemoteInputStream result = istream.export();
// after all the hard work, discard the local reference (we are passing
// responsibility to the client)
istream = null;
return result;
} finally {
// we will only close the stream here if the server fails before
// returning an exported stream
if (istream != null) {
istream.close();
}
}
}
////////////////////////////////////
rmi works on a stub and skeleton structure.
Exception that is thrown has something to do with rmi Registry. The Object is not found because it is not available from RMI resistry.
A NoSuchObjectException is thrown if an attempt is made to invoke a method on an object that no longer exists in the remote virtual machine
as in javaDoc of the Exception thrown
Related
I am asynchronously running the below method to zip the given set of nio paths. When there are multiple tasks running, java heap out of memory exception is encountered.
public InputStream compressToZip(String s3folderName, Set<Path> paths) throws Exception {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream);
paths.forEach(path -> {
try {
System.out.println("Zipping " + path.getFileName());
zos.putNextEntry(new ZipEntry(path.getFileName().toString()));
FileInputStream ObjectInputStream = new FileInputStream(path.toFile());
IOUtils.copy(ObjectInputStream, zos);
zos.closeEntry();
} catch (Exception e) {
...
}
});
zos.close();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} catch (Exception e) {
...
}
}
The input stream returned from this file will be written on sftp location.
org.springframework.integration.file.remote.session.Session session = this.createSession(deliveryType, deliveryLocation);
zippedIpStream = fileCompressionSvc.compressToZip(s3folderName, fileDir);
session.write(zippedIpStream, deliveryLocation.getLocation().getFolder() + "/"
+ getfileNameFormat(fileNameFormat, masterId) + ".zip");
I am not sure what went wrong to occur java heap issue. Could you please assist me.
Changed the implementation to write the file into a file in local path and then send that file to sftp and then delete the temp zip file.
public void compressToZip(String s3folderName, Set<Path> distinctPaths, String efsPathWithFileName) throws Exception {
try(FileOutputStream fos = new FileOutputStream(efsPathWithFileName);
ZipOutputStream zos = new ZipOutputStream(fos)) {
distinctPaths.forEach(path -> {
try {
zos.putNextEntry(new ZipEntry(path.getFileName().toString()));
final FileInputStream fis = new FileInputStream(path.toFile());
IOUtils.copy(fis, zos);
zos.closeEntry();
} catch (IOException e) {
...
}
});
} catch (Exception e) {
...
throw e;
}
}
calling method:
InputStream zippedIpStream = new FileInputStream(tempCompressedFilePath);
session.write(zippedIpStream, deliveryLocation.getLocation().getFolder() + "/" + fileNameToWrite);
...
...
zippedIpStream.close();
...
...
Files.deleteIfExists(Paths.get(tempCompressedFilePath));
Here is an attempt to write to external storage on my device:
private void extract(ZipInputStream zis) throws IOException {
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
if(!entry.isDirectory()) {
writeFile(zis, entry.getName());
}
zis.closeEntry();
}
zis.close();
}
private void writeFile(ZipInputStream zis, String filename) {
/* flag to determine if creation of every directory leading to
* filename was successful */
boolean newDirsSuccess;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
BufferedOutputStream bos = null;
try {
File newFile = new File(Environment.getExternalStorageDirectory(),
"decrompressed/" + filename);
// ignore special files
if(newFile.getName().equals(".DS_Store")||newFile.getAbsolutePath().contains("__") ) {
return;
}
File parentDir = newFile.getParentFile();
// if the file's parent structure isn't there, create it
if (!parentDir.exists()) {
newDirsSuccess = parentDir.mkdirs();
}
// this line throws a FileNotFoundException NOENT
FileOutputStream fos = new FileOutputStream(newFile);
bos = new BufferedOutputStream(fos);
byte[] byteArr = new byte[4096];
int numBytes = 0;
// read from ZipInputStream and rite the bytes
while((numBytes = zis.read(byteArr)) != -1) {
bos.write(byteBuffer, 0, numBytes);
}
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
A FileNotFoundException is thrown when trying to create the FileOutputStream. I want to see the value of newDirsSuccess, but it does not show up in the debugger window so I'm not sure where this exception is coming from.
The "newFile" declaration should have created a new empty file, and parentDir.makeDirs() should have created any directories leading up to this new file, so why is this exception being thrown?
parentDir looked like: "/storage/emulated/0/decompressed/game1_stats"
I lacked the permission to write to external storage. Add this to AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I wanted to Override a file which is used by other process in windows machine using Java Program, for which I want obtain force lock on file , please guide me how can I achieve.
I am using org.apache.commons.io.monitor.FileAlterationObserver to check whether file is changed or not if changed i want to override dest file with src file.
I tried both code snippets I am getting below exception.
Exception :
The process cannot access the file because it is being used by another process
at java.io.RandomAccessFile.open(Native Method)
Code Snippet1
FileAlterationObserver observer = new FileAlterationObserver(folderToObserve);
observer.addListener(new FileAlterationListener() {
#Override
public void onFileChange(File file) {
System.out.println("File changed , file.getAbsolutePath() : "+file.getAbsolutePath());
file.delete();
try {
FileUtils.copyFile(srcFile, file);
//checkAndUpdateFile(srcFile, file);
} catch (Exception e) {
System.out.println("Error In overriding file");
e.printStackTrace();
}
}
Code Snippet2
private static void checkAndUpdateFile(File src, File dest) throws IOException {
FileInputStream in = new FileInputStream(src);
FileChannel srcChannel = in.getChannel();
FileChannel destChannel = null;
FileLock destLock = null;
try {
if (!dest.exists()) {
final RandomAccessFile destFile = new RandomAccessFile(dest, "rw");
destChannel = destFile.getChannel();
destLock = destChannel.lock();
copyFileChannels(srcChannel, destChannel);
dest.setLastModified(src.lastModified());
} else {
final RandomAccessFile destFile = new RandomAccessFile(dest, "rw");
destChannel = destFile.getChannel();
destLock = destChannel.lock();
if (!compareFileChannels(srcChannel, destChannel)) {
copyFileChannels(srcChannel, destChannel);
dest.setLastModified(src.lastModified());
}
}
}
I would like to send file from client to server and be able do it again in the future.
So my client connect to server and upload file, ok - it works but it hangs at the end..
so here is my code in client, the server side is quite similar.
private void SenderFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
IoUtil.copy(fis, os);
} catch (Exception ex) {
ex.printStackTrace();
}
}
IoUtils found on Stack :)
public static class IoUtil {
private final static int bufferSize = 8192;
public static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[bufferSize];
int read;
while ((read = in.read(buffer, 0, bufferSize)) != -1) {
out.write(buffer, 0, read);
}
out.flush();
}
}
Explanation: my client has a socket connected to server, and I send any file to him.
My server download it but hangs at the end because he is listening for more infromation.
If I choose another file, my server will download new data to the existing one.
How could I upload any file to server, make my server work on and be able download another one file properly?
ps. If I add to ioutil.copy at the end of function out.close my server will work on but the connection will be lost. I do not know what to do :{
After update:
Client side:
private void SenderFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
DataOutputStream wrapper = new DataOutputStream(os);
wrapper.writeLong(file.length());
IoUtil.copy(fis, wrapper);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Server side (thread listening for any message from client):
public void run() {
String msg;
File newfile;
try {
//Nothing special code here
while ((msg = reader.readLine()) != null) {
String[] message = msg.split("\\|");
if (message[0].equals("file")) {//file|filename|size
String filename = message[1];
//int filesize = Integer.parseInt(message[2]);
newfile = new File("server" + filename);
InputStream is = socket.getInputStream();
OutputStream os = new FileOutputStream(newfile);
DataInputStream wrapper = new DataInputStream(is);
long fileSize = wrapper.readLong();
byte[] fileData = new byte[(int) fileSize];
is.read(fileData, 0, (int) fileSize);
os.write(fileData, 0, (int) fileSize);
System.out.println("Downloaded file");
} else
//Nothing special here too
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Ok, now I can download file - still once, another one is downloaded but unable to read. For example, second time I want send by client a file.png. I got it on server, but this file is not possible to view.
Thanks in advance :)
You need to make your server able to differentiate files. The easiest way is to tell in advance how many bytes the receiving end should expect for a single file; this way, it knows when to stop reading and wait for another one.
This is what the SenderFile method could look like:
private void SenderFile(File file)
{
try
{
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
DataOutputStream wrapper = new DataOutputStream(os);
wrapper.writeLong(file.length());
IoUtil.copy(fis, wrapper);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
And this is what the ReceiveFile method could look like:
// the signature of the method is complete speculation, adapt it to your needs
private void ReceiveFile(File file)
{
FileOutputStream fos = new File(file);
InputStream is = socket.getInputStream();
DataInputStream wrapper = new DataInputStream(is);
// will not work for very big files, adapt to your needs too
long fileSize = wrapper.readLong();
byte[] fileData = new byte[fileSize];
is.read(fileData, 0, fileSize);
fos.write(fileData, 0, fileSize);
}
Then don't close the socket.
I have java code for file download through ftp, after download the file, it goes to default path. The specified destination path is not having the downloaded file. Why? my code is,
public class ftpUpload1
{
public static void main(String a[]) throws IOException
{
ftpUpload1 obj = new ftpUpload1();
URL url1 = new URL("ftp://vbalamurugan:vbalamurugan#192.168.6.38/ddd.txt" );
File dest = new File("D:/rvenkatesan/Software/ddd.txt");
obj.ftpDownload(dest, url1);
public void ftpDownload(File destination,URL url) throws IOException
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URLConnection urlc = url.openConnection();
bis = new BufferedInputStream( urlc.getInputStream() );
bos = new BufferedOutputStream( new
FileOutputStream(destination.getName() ) );
int i;
//read byte by byte until end of stream
while ((i = bis.read())!= -1)
{
// bos.write(i);
bos.write(i);
}
System.out.println("File Downloaded Successfully");
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
The downloaded file "ddd.txt" not in the "D:/rvenktesan/Software". It is located in "D:rvenkatesan/JAVA PROJECTS". Why? guide me to store the file in specified path? Thanks in adcance.
You problem is FileOutputStream(destination.getName() ) );
change this to: FileOutputStream(destination.getAbsolutePath() ) );
getName wil return the filename "ddd.txt" only. I assume you are starting your app from D:/rvenkatesan/JAVA PROJECTS