I have a requirement where i have to copy a file from my local workspace to a network drive. i have all working credentials to open up the network drive and see, i am using JCIF methods to achieve this but unfortunately when i run the below code am getting the access denied exception
public static void main(String[] args) {
File file = new File("D:\\sampletext.txt");
try {
createCopyOnNetwork("prestige", "sannayalap", "Ci**#***", "D:\\sampletext.txt", "smb://10.28.41.**//d$//CDSBatches//test");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static boolean createCopyOnNetwork(String domain,String username,String password,String src, String dest) throws Exception
{
SmbFileOutputStream out = null;
BufferedInputStream inBuf = null;
try{
NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(domain,username,password); // replace with actual values
SmbFile file = new SmbFile(dest, authentication); // note the different format
inBuf = new BufferedInputStream(new FileInputStream(src));
out = (SmbFileOutputStream)file.getOutputStream();
byte[] buf = new byte[5242880];
int len;
while ((len = inBuf.read(buf)) > 0){
out.write(buf, 0, len);
}
}
catch(Exception ex)
{
throw ex;
}
finally{
try{
if(inBuf!=null)
inBuf.close();
if(out!=null)
out.close();
}
catch(Exception ex)
{}
}
System.out.print("\n File copied to destination");
return true;
}
when i run this am getting this exception
jcifs.smb.SmbException: Access is denied.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:563)
at jcifs.smb.SmbTransport.send(SmbTransport.java:664)
at jcifs.smb.SmbSession.send(SmbSession.java:238)
at jcifs.smb.SmbTree.send(SmbTree.java:119)
at jcifs.smb.SmbFile.send(SmbFile.java:775)
at jcifs.smb.SmbFile.open0(SmbFile.java:992)
at jcifs.smb.SmbFile.open(SmbFile.java:1009)
at jcifs.smb.SmbFileOutputStream.<init>(SmbFileOutputStream.java:142)
at jcifs.smb.SmbFileOutputStream.<init>(SmbFileOutputStream.java:97)
at jcifs.smb.SmbFileOutputStream.<init>(SmbFileOutputStream.java:67)
at jcifs.smb.SmbFile.getOutputStream(SmbFile.java:2856)
at dev.copyFileRemote.createCopyOnNetwork(copyFileRemote.java:36)
at dev.copyFileRemote.main(copyFileRemote.java:141)
if any one have any idea on how to copy files to network drive then please help in this. also please suggest if you know any other alternative approaches to acheive this.
Related
I am trying to make a file manager app in Android.
I want to provide the user with an option to move their files. So first I am copying the Files then I am deleting the file if there is no error.
This is the code I am using to copy the files
public static boolean copy(File copy, String directory, Context con) {
static FileInputStream inStream = null;
static OutputStream outStream = null;
DocumentFile dir = getDocumentFileIfAllowedToWrite(new File(directory), con);
String mime = "";
DocumentFile copy1 = dir.createFile(mime, copy.getName());
try {
inStream = new FileInputStream(copy);
outStream = con.getContentResolver().openOutputStream(copy1.getUri());
byte[] buffer = new byte[16384];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
outStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
But in one of my devices the files are simply getting deleted without copying.
So my thought is that I will check the length of the file by SourceFile.length() and the length of the DestinationFile.length() if both are same or not. If both are same then I will delete the SourceFile.
Is the most effective way to check it without checking the MD5 of an File? Also what are the chances that the file transfer is incomplete/corrupted and still the length is same?
I was trying to implement the functionality of transferring local files to a network drive using jcifs library but upon running the program on the command line I was receiving following exception:
Exception in thread "main" java.lang.NullPointerException
jcifs.smb.ServerMessageBlock.writeString(ServerMessageBlock.java: 202)
To understand the error I tried debugging the code on eclipse and while doing so at line:
NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication("xxxxxx.xx.com",username,password);
I received an exception stating ClassNotFoundException. But I have the jcifs.jar in the build path.
A quick google search for 'ntlmpasswordauthentication' classnotfoundexception landed me on two threads with same issue but no resolution.
Please let me know how can I resolve this.
Thank you
Here is the whole function, just in case needed:
private static void TransferFiles()
{
File transfer_files = new File (sourcepath);
File[] files = transfer_files.listFiles();
String username = properties.getProperty("user");
String password = properties.getProperty("password");
String source = sourcepath;
SmbFileOutputStream outputStream = null;
FileInputStream inputStream = null;
SmbFile copyFile = null;
byte[] buffer = new byte[16*1024*1024];
int length = 0;
jcifs.smb.NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication("xxxxxxx",username,password);
try
{
copyFile = new SmbFile(destinationpath,authentication);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
outputStream = new SmbFileOutputStream(copyFile);
}
catch (SmbException | MalformedURLException | UnknownHostException e)
{
e.printStackTrace();
}
try
{
inputStream = new FileInputStream(sourceFile);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
try
{
while((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close();
outputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
I've made applet, Here's files from its jar.
In my classes I've call ffmpeg.exe, and I have all privileges like self-signed applet and make call via Access Controller. So I've getting error in program, It's can't be find *my ffmpeg lib*.
This should be very easy Q: where should I place my ffmpeg.exe file ?
And I've get exception as:
Cannot run program "ffmpeg": CreateProcess error=2, ?? ??? ??? ????? ????
The code are following as:
public class DtpVideoApplet extends Applet
{
public String startRecording() throws IOException
{
try
{
return(String) AccessController.doPrivileged(new PrivilegedAction<String>()
{
public String run()
{
try
{
Runtime.getRuntime()
.exec("ffmpeg -y -f dshow -i video=\"screen-capture-recorder\" output.flv");
return "Entered";
}
catch (Exception e)
{
// TODO Auto-generated catch block
return e.getMessage();
}
}
});
}
catch (Exception e)
{
return e.getMessage();
}
}
}
I never run an .exe from an applet, however I'm load some .dlls from an applet resource, to do this first I copy my applet resources to temp path and then I load it from this path. The dlls are located inside the jar how is showed below:
loadLib method copies .dlls to disc and then load it, this method receive as parameters the directory and the name of the file (in my case the method call is loadLib("/sun/security/mscapi/","sunmscapi_x32.dll"); )
public static void loadLib(String libraryPath, String libraryName) throws IOException, InterruptedException{
System.out.println(libraryPath + "---------------------");
URL inputStreamLibURL = AddSunMSCAPIProvider.class.getResource(libraryPath);
if(inputStreamLibURL==null){
throw new IOException("Resource not found: " + libraryPath);
}
String tempPath = System.getProperty("java.io.tmpdir", NOT_FOUND);
if(tempPath.equals(NOT_FOUND)){
throw new IOException("Temporary File not found");
}
File tempDir = new File(tempPath);
//first try to overwrite the default file
File defaultFile = new File(tempPath, libraryName);
boolean useDefaultFile = false;
if(defaultFile.exists()){
try{
useDefaultFile = defaultFile.delete();
//return false if the library cannot be deleted (locked)
}catch(Exception e){
e.printStackTrace();
useDefaultFile = false;
}
}else{
useDefaultFile = true;
}
File tempFile;
if(useDefaultFile){
tempFile = defaultFile;
}else{
tempFile = File.createTempFile(libraryName, "", tempDir);
}
copy(inputStreamLibURL.openStream() ,tempFile, 0);
Runtime.getRuntime().load(tempFile.getAbsolutePath());
}
/**
* File copy
* #param src
* #param dest
* #param bufferSize
* #throws IOException
*/
private static void copy(InputStream src, File dest, int bufferSize) throws IOException{
if(bufferSize<=0){
bufferSize = 2000; //default bytebuffer
}
InputStream is = src;
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
byte[] buffer = new byte[bufferSize];
int c;
while((c = is.read(buffer))!= -1){
os.write(buffer, 0, c);
}
is.close();
os.close();
return;
}
Of course in order to do this operations, the applet must be correct signed and necessary MANIFEST permissions added.
Hope this helps,
I'm using the following code to upload an xml file to the directory /home/domainname/public_html/guest in the server. However, the file is uploaded only to the location /home/domainname. It is not uploading to the child directories. Please advise.
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(Util.getProductsXMLFTPServer());
client.login(Util.getProductsXMLFTPUser(), Util.getProductsXMLFTPPassword());
//
// Create an InputStream of the file to be uploaded
//
fis = new FileInputStream(new File(Util.getProductsXMLFTPInputFilePath(), Util.getProductsXMLFTPOutputFileName()));
client.changeWorkingDirectory(Util.getProductsXMLFTPUploadPath());
client.storeFile(Util.getProductsXMLFTPOutputFileName(), fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
I checked your code, it works. I've only changed file type declaration to binary, which may be not needed for XML files.
Here's my complete code for reference:
package apachenet.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class App {
public static void main( String[] args ) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(/*Util.getProductsXMLFTPServer()*/"127.0.0.1");
client.login(/*Util.getProductsXMLFTPUser()*/"pwyrwinski",
/*Util.getProductsXMLFTPPassword()*/"secret");
client.setFileType(FTP.BINARY_FILE_TYPE); // optional
fis = new FileInputStream(
new File(/* Util.getProductsXMLFTPInputFilePath() */"/home/pwyrwinski",
/* Util.getProductsXMLFTPOutputFileName() */"img.png"));
client.changeWorkingDirectory(/*Util.getProductsXMLFTPUploadPath()*/ "someDir");
client.storeFile(/*Util.getProductsXMLFTPOutputFileName()*/"img_bis.png", fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As you can see it's roughly the same as yours.
Util class calls are replaced with raw data.
When I ran it, file /home/pwyrwinski/img.png was uploaded to {FTP_USER_ROOT}/someDir directory on ftp server with name changed to img_bis.png. I assume this is exactly what you wanted to achieve.
Let's go back to your problem.
Try to check what is returned from
Util.getProductsXMLFTPUploadPath() call. My guess is it's not what
you're expecting - so debug it in your IDE or print it to the console.
Check if path returned from Util.getProductsXMLFTPUploadPath()
call starts with slash, it shouldn't.
UPDATE 1.
Does direcory /home/domainname/public_html/guest exist on server?
Add following method to your class:
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
and call it after every ftp-client's method call. This will give you codes and descriptions of every command result. I suspect client.changeWorkingDirectory(...) ends with error, probably: 550 Permission Denied (or No such file or folder).
Next modification will be:
client.login(Util.getProductsXMLFTPUser(), Util.getProductsXMLFTPPassword());
System.out.println(client.printWorkingDirectory()); // added this line!
this will tell us what is current working directory after login in.
Please post your results.
FTPClient ftpClient = new FTPClient();
try {
System.out.println("before server connection");
ftpClient.connect(server, port);
System.out.println("before user name and passwod");
ftpClient.login(user, pass);
ftpClient.enterLocalActiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("connection sucess");
// windows working fine
File secondLocalFile = new File("/home/aims/archived_reports/tes_S_000000123/test.pdf");
// String secondRemoteFile = "/archived_reports/PermanentRecord.pdf";
//linux
// File secondLocalFile = new File("/archived_reports/tes_S_000009123/test.pdf");
String secondRemoteFile = "remotefilename.pdf";
InputStream inputStream = new FileInputStream(secondLocalFile);
System.out.println("Start uploading second file");
ftpClient.changeWorkingDirectory("/reports");// home/ftp.test/reports folder
System.out.println("Prasent Working Directory :"+ftpClient.printWorkingDirectory());
OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
int returnCode = ftpClient.getReplyCode();
System.out.println(returnCode);
byte[] bytesIn = new byte[4096];
int read = 1;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
System.out.println();
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
System.out.println("The second file is uploaded successfully.");
}
Let's say I have an URL, like something.domain/myfile.txt then I want to save this file, with that "Save File" dialog.
I tried my best to do it, but everytime I save the file using the dialog the file is not there.
An example or somewhere I can find information on this would help a lot!
URL website = null;
try {
website = new URL(<insert url here>);
} catch (MalformedURLException e) {
e.printStackTrace();
}
ReadableByteChannel rbc = null;
try {
rbc = Channels.newChannel(website.openStream());
} catch (IOException e2) {
e2.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("minecraft.jar"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (IOException e) {
e.printStackTrace();
}
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File dir = fileChooser.getCurrentDirectory();
dir.mkdir();
//After this point is where I need help.
I trust that this is what you're looking for:
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
// whatever you want to do with the file
System.out.println("The file is "+file.getAbsolutePath());
// fos = new FileOutputStream(file) ...
}
Did you notice that in your code you are trying to save/download the file before giving the user the option to chose the destination?
I would split the code into three different operations:
A method in charge of transferring the bytes from the InputStream (the web) to the OutputStream (the file).
a method to show the user a dialog so he can chose where to store the file.
the method that completes the whole task: choose a file and transfer the bytes from the web to it.
1) Would be something like this (you don't need to use the NIO API to implement it):
public void transfer(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
}
2) would be something very similar to what Dukeling has already stated:
public File chooseFile() {
File result = null;
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
result = fileChooser.getSelectedFile();
}
return result;
}
3) then, combining these two operations together is really simple:
public void saveFileFromWeb(URL url) {
File file = chooseFile(); // 1. Choose the destination file
if (file != null) {
// 2. Create parent folder structure
File folder = file.getParentFile();
if (!folder.exist()) {
folder.mkdirs();
}
InputStream in = null;
OutputStream out = null;
try {
// 3. Initialise streams
in = url.openStream();
out = new FileOuputStream(file);
// 4. Transfer data
transfer(in, out);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 5. close streams
if (in != null) {
try {
in.close();
} catch (IOException e) { /* ignore */ }
}
if (out != null) {
try {
out.close();
} catch (IOException e) { /* ignore */ }
}
}
}
NOTE: 1) and 2) could be private methods. Of course you could do this is just one single operation but splitting it would give you an overview of the different steps to perform.
NOTE 2: I simplified the exception handling part