File path working in NetBeans but not in built JAR file - resources

I am trying to copy file from classpath to user specified location. However, While running program in netbeans, file path works correctly and file gets copied but when I build a jar file and try the same, it doesnt locates source file.
URL url = getClass().getResource("utils/mount");
File file = new File(url.getPath());
this.copyEachFile(url.getPath(), "C:\\Users\\Nikhil\\Desktop\\" + mount); //this function takes in source path of file and copies it to destination path.
when I trace source path I get
/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/build/classes/aroma/installer/utils/mount
in netbeans and following in jar
/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/dist/Aroma-Installer.jar!/aroma/installer/utils/mount
When I run program in netbeans, file successfully copies but while running through jar, it says source doesnt exist.
Where is the problem?

Okay so I created a function and called it as follows.
this.copyFileFromJar("utils/mount", "C:\\Users\\Nikhil\\Desktop\\mount");
Definition of function is as follows.
public void copyFileFromJar(String source, String destination) throws IOException{
File dest = new File(destination);
if(!dest.exists()){
dest.createNewFile();
}
InputStream in = null;
OutputStream out = null;
try{
in = this.getClass().getResourceAsStream(source); //Important step, it returns InputStream which can be manipulated as per need.
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
JOptionPane.showMessageDialog(null, "File Successfully copied at" + dest.getAbsolutePath());
System.out.println("File Writing......" + dest.getName());
}
finally{
in.close();
out.close();
}
}
And now I am able to copy files from jar file to user specified location.
Hope this helps anybody who is looking for same kind of problem.

Related

Kentico 11 - MediaFileInfoProvider.DeleteMediaFileInfo Not Deleting

MediaFileInfo updateFile = MediaFileInfoProvider.GetMediaFileInfo(library.LibraryID, file.Name);
The above line of code is not removing the file from the media library as I expected. This is for a Scheduled Task in Kentico 11 MVC. The new file does get created and is renamed by the System to prevent conflicts.
I would like to delete the existing file before importing the updated version of the file. I would even be satisfied if the new file overwrote the existing file.
public void UpdateMediaFile(MediaLibraryInfo library, string fileName, string importPath)
{
//LumberMarketReport.pdf and PanelMarketReport.pdf
if (library != null)
{
// Prepares a path to a local file
string filePath = fileName;
// Prepares a CMS.IO.FileInfo object representing the local file
CMS.IO.FileInfo file = CMS.IO.FileInfo.New(filePath);
if (file != null)
{
#region "Delete Existing"
MediaFileInfo updateFile = MediaFileInfoProvider.GetMediaFileInfo(library.LibraryID, file.Name);
if (updateFile != null)
{
MediaFileInfoProvider.DeleteMediaFileInfo(updateFile);
}
#endregion
#region "Create File"
// Creates a new media library file object
MediaFileInfo mediaFile = new MediaFileInfo(filePath, library.LibraryID);
// Sets the media library file properties
mediaFile.FileName = file.Name;
mediaFile.FileDescription = "This file was added through the API.";
mediaFile.FilePath = "/"; // Sets the path within the media library's folder structure
mediaFile.FileExtension = file.Extension;
mediaFile.FileMimeType = MimeTypeHelper.GetMimetype(file.Extension);
mediaFile.FileSiteID = SiteContext.CurrentSiteID;
mediaFile.FileLibraryID = library.LibraryID;
mediaFile.FileSize = file.Length;
if (file.Name == "PanelMarketReport.pdf")
{
mediaFile.FileTitle = "Panel Market Report";
mediaFile.SetValue("FileCategoryID", 19);
}
else if (file.Name == "LumberMarketReport.pdf")
{
mediaFile.FileTitle = "Lumber Market Report";
mediaFile.SetValue("FileCategoryID", 57);
}
// Saves the media library file
MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
#endregion
}
}
}
I would add logging to make sure your code is getting hit. Make sure updatefile isn't null. I think you have to pass in the file path in the media library and not just the name.
If I am not mistaken MediaFileInfoProvider.DeleteMediaFileInfo will remove a record from DB but not physically delete the file, so you need to call CMS.IO.FileInfo.Delete(filePath) to delete it from disk.

I have my own code to create a excel file and I want to send that as an attachment to email without saving file in local system

I am working on a case where I will be supplied with data and I will create a excel file using that data.
Right now I am creating it in my local system and later adding that as an attachment and sending through email using Java Mail Service.
But I dont want to store excel file in my local system and I want to just pass the stream object to email service and send email. So that there wont be any local storage of file still able to send attachment.
Please reply if there is any solution ?
// Created WorkBook
HSSFWorkbook workbook = new HSSFWorkbook();
FileOutputStream outputStream = new FileOutputStream(FILE_NAME)) workbook.write(outputStream);
here FILE_NAME is fully qualified system path where I will be storing file.
I want to skip this and directly send attachment
I'm using an approach like this and it is working fine:
File file = File.createTempFile("Report", "xlsx");
file.deleteOnExit();
Path path = file.toPath();
try (final FileOutputStream fileOut = new FileOutputStream(file)) {
try (final XSSFWorkbook workbook = new XSSFWorkbook()) {
//create your sheets here
workbook.write(fileOut);
return Files.readAllBytes(path);
} catch (Exception e) {
LOG.error("Error during creation of excel report", e);
throw e;
} finally {
if (path != null) {
try {
Files.delete(path);
} catch (final IOException e) {
LOG.error("Unable to delete file:" + path.toString(), e);
}
}
}
}
Write the data to a ByteArrayOutputStream, get the bytes, and use a ByteArrayDataSource to supply the data to JavaMail:
mbp.setDataHandler(new DataHandler(
new ByteArrayDataSource(bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")));
Workbook workbook=new XSSFWorkbook();
Sheet sheet =workbook.createSheet(" ");
Font HearderFont=workbook.createFont();
HearderFont.setBold(true);
HearderFont.setFontHeightInPoints((short)9);
HearderFont.setColor(IndexedColors.RED.getIndex());
CellStyle hearderCellStyle=workbook.createCellStyle();
hearderCellStyle.setFont(HearderFont);
//excel file maker
int rownum=1;
for(MailModelClass mailModelonbj:dataStored) {
Row row=sheet.createRow(rownum++);
row.createCell(0).setCellValue(mailModelonbj.(any));
row.createCell(1).setCellValue(mailModelonbj.(any));
row.createCell(2).setCellValue(mailModelonbj.(any));
}

Download user selected file/upload a file to a user selected directory both with primefaces

I want to download user selected files with primefaces. I was able to do so for a specific file as described in the primface showcase for "file Download". But what I actually want is, that after pressing the "download Button" a file dialog should open, so the user can select a file for himself to download. Is that possible?
My current code for a specific file download lokks like this:
public void handleLanguageFileDownload() throws FileNotFoundException, IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
File fileToDownload = new File(DataManager.configreader.getLang_source());
String fileName = fileToDownload.getName();
String contentType = ec.getMimeType(fileName);
int contentLength = (int) fileToDownload.length();
ec.responseReset();
ec.setResponseContentType(contentType);
ec.setResponseContentLength(contentLength);
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream output = ec.getResponseOutputStream();
Files.copy(fileToDownload.toPath(), output);
fc.responseComplete();
}
I want the exact same behaviour for file upload, so the user can select the folder to upload files to for himself. My current implementation uploads the file only to a specific folder.
My current code for uploading files to a specific folder looks like this:
public void handleLanguageFileUpload(FileUploadEvent event) throws IOException {
if (!this.role.canManageLanguage){
return;
}
String [] filePathParts = DataManager.configreader.getLang_source().split("/");
String uploadPathString = DataManager.configreader.getLang_source().replaceAll(filePathParts[filePathParts.length - 1],""); //event.getFile().getFileName()
File uploadPath = new File(uploadPathString);
File fileToUpload = new File(uploadPath, event.getFile().getFileName());
try (InputStream input = event.getFile().getInputstream()) {
if(event.getFile().getFileName().equals(filePathParts[filePathParts.length - 1])) { //fileToUpload.getName()
Files.copy(input, fileToUpload.toPath(), StandardCopyOption.REPLACE_EXISTING);
uiManager.userMessage.info (event.getFile().getFileName() + " " + this.translate("msg_has_been_uploaded") + " !");
this.getOwnTreeVersion();
}
else {
uiManager.userMessage.error (event.getFile().getFileName() + " " + this.translate("msg_is_wrong_cannot_be_uploaded") +": " + filePathParts[filePathParts.length - 1] + " !");
}
}
}
Thank you in advance for your help!!!
working with file chooser is only possible with the Upload method look at this post to understand how to implement it in your project Upload File Step by Step and you can even read more in the Primefaces web site Primefaces Upload File if you need to add a FileSizeLimite and many other features.
Now for the download method i told you that it's impossible because you have a default file location (generally it's Download) you can read more about it in the Primefaces web site Primefaces Download File you can set it manually but it will not be dynamic look at this post Change Download Path.

Emgu CV C# Exception creating tesseract object

I can access all emgu libraries. VS finds the libraries and using Emgu.CV.OCR returns no errors.
When I try to create a Tesseract object, Program.cs throws a FileLoadException. in System.Windows.Forms.dll.
Removing the line of code that creates a tesseract lets the program run fine.
I have tried copying tessdata to my debug file and that also has not worked.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}
I fiddled with the same problem for a while; now I got it.
First, make sure you have the following using directives (you might need to download Emgu.CV via NuGet):
using Emgu.CV;
using Emgu.CV.OCR;
using System.Reflection;
using System.IO;
using System.Drawing;
Then, make sure you have the most up-to-date tessdata on board. If not, navigate to github and download it (click "Clone or Download" and select "Download ZIP File"). You should then unzip the file and rename the folder "tessdata-master" to "tessdata." Copy this folder to the place where your binary lives (the assembly location).
Lastly, assign the correct path, and you're ready to do OCR!
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";
var _ocr = new Tesseract(path, "eng", OcrEngineMode.Default);
_ocr.SetImage(yourImage);
_ocr.Recognize();
var result = _ocr.GetCharacters();
First you need to check your project References . Is there "Emgu.CV.OCR" library if not kindly add it first. Then try the following code may it will work for you.
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"C:\Emgu\emgucv-windows-universal-cuda 2.9.0.1922\Emgu.CV.OCR\tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);//first Parameter set your path ..complete path like i did
_ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopkrstuvwxyz");
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}

How to zip and unzip folders and its sub folders in Silverlight?

I have a Windows Phone application. I am using SharpZipLib to zip folders and its sub folders. This is zipping only the folder but the data inside the folders is not getting zipped. Can anyone guide me how to do this?
My code:
private void btnZip_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string filename in appStore.GetFileNames(directoryName + "/" + "*.txt"))
{
GetCompressedByteArray(filename);
}
textBlock2.Text = "Created file has Zipped Successfully";
}
}
public byte[] GetCompressedByteArray(string content)
{
byte[] compressedResult;
using (MemoryStream zippedMemoryStream = new MemoryStream())
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(zippedMemoryStream))
{
zipOutputStream.SetLevel(9);
byte[] buffer;
using (MemoryStream file = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
buffer = new byte[file.Length];
file.Read(buffer, 0, buffer.Length);
}
ZipEntry entry = new ZipEntry(content);
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, 0, buffer.Length);
zipOutputStream.Finish();
}
compressedResult = zippedMemoryStream.ToArray();
}
WriteToIsolatedStorage(compressedResult);
return compressedResult;
}
public void WriteToIsolatedStorage(byte[] compressedBytes)
{
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
appStore.CreateDirectory(ZipFolder);
using (IsolatedStorageFileStream zipTemplateStream = new IsolatedStorageFileStream(ZipFolder+"/"+directoryName + ".zip", FileMode.OpenOrCreate, appStore))
using (BinaryWriter streamWriter = new BinaryWriter(zipTemplateStream))
{
streamWriter.Write(compressedBytes);
}
}
I think you'll find this guide helpful.
An excerpt from the above link
The ZipFile object provides a method called AddDirectory() that
accepts a parameter directoryName. The problem with this method is
that it doesn't add the files inside the specified directory but
instead just creates a directory inside the zip file. To make this
work, you need to get the files inside that directory by looping thru
all objects in that directory and adding them one at a time. I was
able to accomplish this task by creating a recursive function that
drills through the whole directory structure of the folder you want to
zip. Below is a snippet of the function.
I guess you too are facing the same problem where the folder is added to the zip file, but the contents and sub folders are not zipped.
Hope this helps.
Have a look over here for a code sample on how to use SharpZipLib to zip a root folder including nested folders.

Resources