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();
}
Related
I'm having some trouble with transferring files to my ftp.
with this code i get no errors, but I also don't get a file to my ftp server. I hope some more experienced users can point me to the right direction.
FTPClient client = new FTPClient();
FileInputStream picture = null;
try {
client.connect("adress" ,port);
client.login("user", "password");
client.changeWorkingDirectory("/htdocs/javaprojekt");
client.setFileType(FTP.BINARY_FILE_TYPE);
String filename = "/Users/sicknk/Documents/Java Projekt/fyeah.jpg";
picture = new FileInputStream(filename);
client.storeFile(filename, picture);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (picture != null) {
picture.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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.
I am trying to create kmz file from kml file on the fly and render it as a stream of bytes in web application.
But when I downloaded generated kmz file, I couldn't open it using archive manager on Ubuntu.
I view similar questions on this site, but it don't work.
Can someone help me and explain what I do wrong?!
This is my code.
#Public public void retrieveKmlInOldFormat() {
File file = new File(Play.applicationPath+"/"+Play.configuration.getProperty("web.content", "../bspb-web")+"/map/map.kml");
String kmlFileContent = null;
try {
String kmlUrl = file.toURI().toURL().toString();
kmlFileContent = BSPBKml2OldFormatConverter.toOldKml(
kmlParserLocal.load(kmlUrl));
} catch (MalformedURLException e) {
e.printStackTrace();
}
String zippedFileName = "old_fmt_map.kmz";
String zippedKml = compressKmlFile(kmlFileContent,zippedFileName);
response.setContentTypeIfNotSet("application/vnd.google-earth.kmz");
renderBinary(new ByteArrayInputStream(zippedKml.getBytes()),zippedFileName);
return;
}
Compress method code:
private String compressKmlFile(String kmlFileContent,String zipEntryName){
String zippedContent = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ZipOutputStream zipStream = new ZipOutputStream(new
BufferedOutputStream(byteStream));
ZipEntry zipEntry = null;
zipEntry = new ZipEntry("doc.kml");
try {
zipEntry.setSize(kmlFileContent.getBytes("UTF-8").length);
zipStream.putNextEntry(zipEntry);
zipStream.write(kmlFileContent.getBytes("UTF-8"));
zipStream.closeEntry();
zippedContent = new String(byteStream.toByteArray(),"UTF-8");
} catch (IOException e) {
logger.error("Error while zipping kml file content");
}
finally {
try {
byteStream.close();
zipStream.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return zippedContent;
}
The problem is about downloaded corrupted kmz archive. This problem can be resolved by using output stream of http response as constructor argument for ZipOutputStream class.
Solution is in this code.
#Public public void retrieveKmlInOldFormat(){
File file = new File(Play.applicationPath+"/"+Play.configuration.getProperty("web.content", "../bspb-web")+"/map/map.kml");
String kmlFileContent = null;
try {
String kmlUrl = file.toURI().toURL().toString();
kmlFileContent = BSPBKml2OldFormatConverter.toOldKml(kmlParserLocal.load(kmlUrl));
} catch (MalformedURLException e) {
e.printStackTrace();
}
response.setContentTypeIfNotSet("application/vnd.google-earth.kmz");
response.setHeader("Content-Disposition", "attachment; filename=\"old_fmt_map.kmz\"");
renderAsKmz(response, kmlFileContent,"old_fmt_map.kml");
return;
}
private void renderAsKmz(Response response,String kmlFileContent,String zipEntryName){
ZipOutputStream zipStream = new ZipOutputStream(response.out);
ZipEntry zipEntry = new ZipEntry(zipEntryName);
try {
zipStream.putNextEntry(zipEntry);
zipStream.write(kmlFileContent.getBytes());
} catch (IOException e) {
logger.error("Error while zipping kml file content : " + e.getMessage());
}
finally {
try {
zipStream.closeEntry();
zipStream.close();
} catch (IOException e) {
logger.error("Error while closing zipped stream : " + e.getMessage());
}
}
I have the below 2 methods, supposed to read and write to a file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list) {
#SuppressWarnings("unused")
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
When I'm calling the above methods I'm getting this error:
02-15 10:28:48.165: E/log activity(1743): Can not read file: java.io.FileNotFoundException: /jokesBody1.bjk: open failed: ENOENT (No such file or directory)
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
File file = new File("jokesBody1.bjk");
Why I'm getting this error? I know that I'm missing something small - probably a piece of code that creates the file(I'm not sure), but as a beginner, I'm not able to spot the issue.
File file = new File("jokesBody1.bjk");
Just creates a File objects that points to that path, but no actual file.
Use
file.createNewFile();
To actually create the file.
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
Actually, no. It only creates a File object, an then java assumes that file to exist.
I'm still receiving 1st file my app generated for me.
First , I thought it's because the file exists so I wrote
File file=new File(getCacheDir(), "Competition.xls");
if (file.exists()) {file.delete(); file =new File(getCacheDir(), "Competition.xls");}
But that didn't help me-I still receive first file that was made
I'm new to working with files so I decided to copy entire method here. Sorry for a lot of text.
private void createFileTosend() {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
File toSend=null;
try {
toSend = getFile();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStream = new FileInputStream(toSend);
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
public File getFile() throws IOException, WriteException{
File file=new File(getCacheDir(), "Competition.xls");
if (file.exists()) {file.delete(); file =new File(getCacheDir(), "Competition.xls");}
WritableWorkbook workbook = Workbook.createWorkbook(file);
//then goes long block with creating a .xls file which is not important
workbook.write();
workbook.close();
return file;
}
Help on understanding where the problem is
You should never have a structure like :
catch(Exception ex ) {
//ignore (or log only)
}
Exception are there to tell you something went wrong. What you do is called (in french) "eating/hiding exceptions". You are loosing this very important information that something went abnormally.
You should always either throw the exception you catch to your caller, or process it locally. At the very least, and this is a poor practice, you should log it. But doing nothing is just very wrong.
Here, put the whole try catch in a method for instance :
private void createFileTosend() throws IOException {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
File toSend = getFile();
inputStream = new FileInputStream(toSend);
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
} finally {
try {
if( inputStream != null ) {
inputStream.close();
}
} catch (IOException ioe) {
Log.e( ioe );
}
try {
if( outputStream != null ) {
outputStream.close();
}
} catch (IOException ioe) {
Log.e( ioe );
}
}
}
And now, when you call createFileToSend, do that in a try/catch structure and toast a message, or something if you catch an exception.