On a server side I have a class that I use for convertion SVG file to PDF.
public class PdfHandler {
private File savedFile;
private File svgTempFile;
public PdfHandler(String fileName) {
this.savedFile = new File(File.separator + "documents" + File.separator + fileName);
}
public void convertToPdf(String inputFileName) {
this.svgTempFile = new File(inputFileName);
System.out.println(inputFileName);
if (this.svgTempFile.exists()){
System.out.println("Svg File exists");
}
else {
System.out.println("Svg File not exists");
}
try {
Transcoder transcoder = new PDFTranscoder();
System.out.println("Transcoder created");
FileInputStream fis = new FileInputStream(this.svgTempFile);
System.out.println("Input stream created");
FileOutputStream fos = new FileOutputStream(this.savedFile);
System.out.println("Output stream created");
TranscoderInput transcoderInput = new TranscoderInput(fis);
System.out.println("Transcoder input created");
TranscoderOutput transcoderOutput = new TranscoderOutput(fos);
System.out.println("Transcoder output created");
transcoder.transcode(transcoderInput, transcoderOutput);
System.out.println("Conversion finished");
fis.close();
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Exception");
} finally {
this.svgTempFile.delete();
System.out.println("File deleted");
}
System.out.println("End of method");
}
}
And I have a method that called by RPC.
public String generatePdf(PayDoc filledDoc) {
//String svgFileName = this.generateSvg(filledDoc);
//String pdfFileName = this.generateFileName("pdf");
PdfHandler pdfHandler = new PdfHandler("myPdf.pdf");
pdfHandler.convertToPdf(File.separator + "documents" + File.separator + "mySvg.svg");
return null;//pdfFileName;
}
In eclipse all works fine, but not on Tomcat. RPC fails when I call it on Tomcat
This is Tomcat console output:
\documents\mySvg.svg
Svg File exists
Transcoder created
Input stream created
Output stream created
Transcoder input created
Transcoder output created
File deleted
After that in "documents" folder I have "mySvg.svg"(still not deleted) and "myPdf.pdf"(it is empty).
Looks like you're not including the required library in your deployed application.
ElementTraversal is part of xml-apis-X.XX.X.jar and has to be bundled with your application.
As there are loads of build tools and I don't know which one you're using, I can't suggest changes.
Related
I made program which writes the configuration of the settings to a text file in the directory of the Java executable. The method which writes the file is below.
public class ConfigWriter {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("MyFile.txt", false);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write(args[0]);
bufferedWriter.newLine();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void Config(String[] settings, String[] filenames) {
System.out.println("Settings: "+Arrays.toString(settings));
String[] configurations = new String[settings.length+filenames.length];
int c=0;
for(int i=0;i<settings.length;i++){
configurations[i]= settings[i];
c++;
}
for(int j=0;j<filenames.length;j++){
configurations[c++]= filenames[j];
}
try {
FileWriter writer = new FileWriter("ConfigFile.txt", false);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(int i=0; i<configurations.length; i++){
bufferedWriter.write(configurations[i]);
bufferedWriter.newLine();
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When this method is called it typically writes a file named Config.txt file to the directory where the executable is.
However, while this seems to work for the Windows version of the App. the Mac version of the app seems to be having some issues with the latest update of the MACOS. This Config.txt file can be created from on MAC but I need to run the Java executable from the command line. Any thoughts as to why the Config.txt file is created when running the Java executable from the command line but not when click on it as an app?
I have attached the script where Config method is called below:
button.setOnAction( e -> {
//System.out.println("Running Proteinarium");
//System.out.println(ProjectName.getText());
if(ProjectName.getText() != null){
Projectname = ProjectName.getText();
}
if(GS1FileLocation!=null && GS2FileLocation!=null){
filenames = new String[]{GS1FileLocation, GS2FileLocation, "projectName="+Projectname};
ConfigWriter.Config(Settingsarray, filenames);
final ProteinariumThread service = new ProteinariumThread();
service.start();
window.setScene(scene2);
textArea.appendText("Proteinarium Running see " + fileName+ " for additional information on the Proteinarium Run... \n");
}
else if(GS1FileLocation!=null){
filenames = new String[]{GS1FileLocation,"projectName="+Projectname};
ConfigWriter.Config(Settingsarray, filenames);
final ProteinariumThread service = new ProteinariumThread();
service.start();
window.setScene(scene2);
textArea.appendText("Proteinarium Running see " + fileName+ " for additional information on the Proteinarium Run... \n");
}
else if(GS2FileLocation!=null){
filenames = new String[]{GS2FileLocation,"projectName="+Projectname};
ConfigWriter.Config(Settingsarray, filenames);
final ProteinariumThread service = new ProteinariumThread();
service.start();
window.setScene(scene2);
textArea.appendText("Proteinarium Running see " + fileName+ " for additional information on the Proteinarium Run... \n");
}
else{
System.out.println("No Genesetfile recorded");
Alert dg = new Alert(Alert.AlertType.INFORMATION);
dg.setTitle("Proteinarium Information");
dg.setContentText("Please Specify a Geneset File");
dg.show();
}
}
);
Maybe instead of
new FileWriter("MyFile.txt", false);
try
new FileWriter(new File("MyFile.txt").getAbsolutePath(), false);
I'm not sure if that will fix the issue, but it might be a path problem
i use this code to create a zip of the contents of the application data folder
public static void zipFolder(File inputFolder) {
try {
File srcFile = inputFolder;
File[] files = srcFile.listFiles();
FileOutputStream fos = new FileOutputStream(new File(inputFolder, "toSend.zip"));
ZipOutputStream zos = new ZipOutputStream(fos);
Log.d("", "Zip directory: " + srcFile.getName());
for (File file : files) {
Log.d("", "Adding file: " + file.getName());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(file.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException ioe) {
Log.e("", ioe.getMessage());
}
}
when calling it in regular code it works fine, however i want to run this when the application crashes along with other logging code i run inside an overridden Thread.UncaughtExceptionHandler
in this case the file is created but it keeps growing indefinitely until i force close the application
when following the flow with the debugger i see the files being zipped (File[] files) are just those i expect and i manage to get out of the function call (on to execute the following code) so i don't think it's the function falling into an endless loop
public class MyApplication extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
//here and anywhere else in the code it manages to create a valid zip file with the folder contents
File toZip = getExternalFilesDir(null);
MyUtils.zipFolder(toZip);
if (Costanti.SETTINGS_MAKE_CRASH_LOG)
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
#Override
public void uncaughtException (Thread thread, Throwable e)
{
e.printStackTrace();
File logFolder = getExternalFilesDir(null);
Log.d("Dump logcat from UncaughtExceptionHandler");
String filepath = getExternalFilesDir(null) + "/logcat.txt";
String cmd = "logcat -d -f "+filepath;
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException ee) {
Log.d("Dump skipped");
}
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
File file = new File(logFolder, "LOG-"+ MyUtils.getTSsemicompact());
try {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(errors.toString());
myOutWriter.close();
fOut.close();
} catch (Exception e1) {
e1.printStackTrace();
}
File toZip = getExternalFilesDir(null);
MyUtils.zipFolder(toZip);
//calling this because otherwise it would just stay stuck on the broken activity where the crash occurred
System.exit(0);//when debugging i can reach this line
}
});
}
public static Context getContext() {
return mContext;
}
}
I would like for my app to create a folder on the sd card and save a file in it. This is what I have right now that just saves it in my app data.
File file = new File(context.getExternalFilesDir(""), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
How would I do that?
Alright so I did this. Am I even doing this right?
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "";
File file = new File(fullPath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
Your best option is to use Environment.getExternalStorageDirectory() to find the root path to use.
However, please note that this is not nessasarily the sd-card, from the docs:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
Example, just change your first line to be:
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Need a directory?:
File dir = new File(Environment.getExternalStorageDirectory(), "yourdir");
dir.mkDirs();
File file = new File(dir, fileName);
Try this, Create file folder like this
String fullPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Foldername";
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
Using below program i am able to upload zip file on ftp server.
But it makes the copy of the zip file and upload the file on ftp server.
I want it should delete the file from local system and copy it to server i.e. it should move the file not copy.Please guide
public class UploadFile {
public static void main(String args[])
{
FTPClient ftp=new FTPClient();
try {
int reply;
ftp.connect("ipadddress");
ftp.login("abc", "abc");
reply = ftp.getReplyCode();
System.out.println("reply1" + reply);
if(!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
}
System.out.println("FTP server connected.");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
InputStream input= new FileInputStream("D:\\testencrypted.zip");
String dirTree="/Vel";
boolean dirExists = true;
String[] directories = dirTree.split("/");
for (String dir : directories )
{
if (!dir.isEmpty() )
{
if (dirExists)
{
dirExists = ftp.changeWorkingDirectory(dir);
}
else if (!dirExists)
{
System.out.println("dir tree" + ftp.printWorkingDirectory());
if (!ftp.makeDirectory(dir))
{
throw new IOException("Unable to create remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'");
}
if (!ftp.changeWorkingDirectory(dir))
{
throw new IOException("Unable to change into newly created remote directory '" + dir + "'. error='" + ftp.getReplyString()+"'");
}
System.out.println("dir tree" + ftp.printWorkingDirectory());
}
}
}
ftp.storeFile(dirTree+"/t1.zip",input);
input.close();
ftp.logout();
}
catch(Exception e)
{
System.out.println("err"+ e);
}
finally
{
if(ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch(Exception ioe)
{
}
}
}
}
}
So, once you've completed the upload (and you're sure that it was sucessful, simply use File.delete() to remove the file from the local disk.
File sourceFile = new File("D:\\testencrypted.zip");
InputStream input= new FileInputStream(sourceFile);
// Upload the file...
// Make sure you close the input stream first ;)
if (!sourceFile.delete()) {
System.out.println("Failed to delete " + sourceFile + " from local disk");
sourceFile.deleteOnExit(); // try and delete on JVM exit...
}
I want to create a .txt file and store it on the external storage of the Android phone. I added the permission to my Android Manifest. When I run the code it doesn't give me any error but the file is never created. Not sure what I am doing wrong.
public void createExternalStoragePrivateFile(String data) {
// Create a path where we will place our private file on external
// storage.
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = null;
OutputStreamWriter out = null;
os = myContext.openFileOutput(data, Context.MODE_PRIVATE);
out = new OutputStreamWriter(os);
out.write(data);
os.close();
if(hasExternalStoragePrivateFile()) {
Log.w("ExternalStorageFileCreation", "File Created");
} else {
Log.w("ExternalStorageFileCreation", "File Not Created");
}
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
you need an appropriate permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(data);
out.close();
}
I was able to create the file on the external storage by using the code below:
public void createExternalStoragePrivateFile(String data) {
// Create a path where we will place our private file on external
// storage.
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(data);
out.close();
if(hasExternalStoragePrivateFile()) {
Log.w("ExternalStorageFileCreation", "File Created");
} else {
Log.w("ExternalStorageFileCreation", "File Not Created");
}
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}