File is not created on Mac - java

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

Related

Get logcat to display the entire downloaded HTML

I want my logcat to show entire fetched HTML code not just some part of
it as i'm using regex to dynamically find certain resources.
I have tried to print the fetched HTML into a text file(on PC not on the
android device) but nothing seem to work.
The text file is just for rough work while working with the HTML so that can get the regular expression.
private void writeToFile(String data)
{
try
{
OutputStream outputStream=new FileOutputStream("getNames.txt");
Writer outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch(Exception e)
{
Log.i("EXCEPTION",e.toString());
}
}
can you guys please show how to do file handling properly in android studio.
below should work, for printing log use any mode you would like use, I have shown all in catch block.:
private void writeToFile(String data)
{
try (FileWriter writer = new FileWriter("getNames.txt");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(data);
}
catch(Exception e)
{
Log.i("EXCEPTION",e.getMessage()); //print in info mode
Log.d("EXCEPTION",e.getMessage()); //print in debug
Log.e("EXCEPTION",e.getMessage()); //print error
}
}
OR create file object where you have permission to write or give permission to writable.change path name of your system.
private void writeToFile(String data)
{
File file = new File("C:\\Users\\user\\OneDrive\\Desktop\\test\\getNames.txt");
file.setWritable(true);
try (FileWriter writer = new FileWriter("getNames.txt");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(data);
}
catch(Exception e)
{
Log.i("EXCEPTION",e.getMessage()); //print in info mode
Log.d("EXCEPTION",e.getMessage()); //print in debug
Log.e("EXCEPTION",e.getMessage()); //print error
}
}

Deploying GWT application on Apache Tomcat

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.

Error While running Sqoop Export through java

I have a java program to run export command. While executing the export, it tries to look for the export directory in my local machine instead of Hdfs. The same program works fine for import. I have checked the file exists on hdfs.
Please help.
Below is the code I am executing:
public void executeSqoopLoad() throws UnsupportedEncodingException{
SqoopOptions options = new SqoopOptions();
String driver = "oracle.jdbc.driver.OracleDriver";
//options.setDriverClassName(driver);
options.setUsername(“user");
options.setPassword(“pass");
options.setConnectString("jdbc:oracle:thin:#host:1522:rptdev");
Configuration configuration = new Configuration(false);
Resource configResource;
try {
configResource = FileUtils.getFileResource("/Users/Moiz/git/jef/hadoop/hdfs-site.xml");
configuration.addResource(configResource.getInputStream());
configResource = FileUtils.getFileResource("/Users/Moiz/git/jef/hadoop/core-site.xml");
configuration.addResource(configResource.getInputStream());
FileSystem dfs = FileSystem.get(configuration);
String[] uriSplit = dfs.getUri().toString().split(":");
String newUri = uriSplit[0]+":"+uriSplit[1];
dfs.setWorkingDirectory(new Path(newUri+"/tmp"));
System.out.println(dfs.getWorkingDirectory());
System.out.println("Exists = " + dfs.exists(dfs.getWorkingDirectory()));
DateTime dt = new DateTime();
options.setCodeOutputDir("/tmp");
options.setClassName("SqoopLoad_"+null+dt.getYear()+dt.getMonthOfYear()+dt.getDayOfMonth()+dt.getMillisOfDay());
options.setVerbose(true);
// HDFS options
options.setExportDir(dfs.getWorkingDirectory()+"/TestDirectory");
System.out.println("Exists = " + dfs.exists(new Path(options.getExportDir())));
options.setInputFieldsTerminatedBy('\u0005');
options.setTableName(“SCHEMA.TEST_SQP");
options.setNumMappers(1);
options.setDirectMode(true);
System.setProperty(Sqoop.SQOOP_RETHROW_PROPERTY, "rethrow");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int ret = 100;
try{
ret = new ExportTool().run(options);
}catch (Exception e) {
System.out.println("Debug");
e.printStackTrace();
}
System.out.println("return code "+ ret);
}
java.lang.RuntimeException: java.io.FileNotFoundException: File
/tmp/TestDirectory/part-m-00000 does not exist
I got it to work. Had to re-import the sqoop jars through maven.

Java: Redirecting output of .bat file in other text file using exec() method?

Java is new to me.
I am executing a batch file using Runtime.getRuntime.exec(filename.bat) and this batch file executes a commandant encrypt.password -Dvalue=somevalue>log.txt and redirects its output to a log.txt file.
Problem that I am facing is batch file is working fine if I run it manually however when program executes it ,it just creates blank 'log.txt'
Content of mybat.bat batch file is as below:
cd/
c:
cd c:/ant_builds/thinclient
ant encrypt.password -Dvalue=someValue >C:/log.txt
Java code is as below:
Process p=Runtime.getRuntime.exec("C:\mybat.bat");
p.waitFor();
It seems that after creating the log file,meantime command is executing control comes out from process.
I have read almost 50 threads here however did not get the solution. Please help me out.
Use ProcessBuilder to create your process and call redirectOutput(File) to redirect and append output to a file.
Try this code:
public class Test {
ProcessBuilder builder;
Path log;
public Test() {
try
{
log = Paths.get("C:\\log.txt");
if (!Files.exists(log))
{
Files.createFile(log);
}
builder = new ProcessBuilder("ant", "encrypt.password", "-Dvalue=someValue");
builder.directory(Paths.get("C:\\ant_builds\\thinclient").toFile());
builder.redirectOutput(ProcessBuilder.Redirect.appendTo(log.toFile()));
builder.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
For jdk 1.6 or less, use the following code:
public class Test {
ProcessBuilder builder;
Path log;
Process process;
BufferedReader br;
PrintWriter pw;
Charset charset = Charset.forName("UTF-8");
public Test() {
try {
log = new File("C:\\log.txt");
if (!log.exists()) {
log.createNewFile();
}
builder = new ProcessBuilder("ant", "encrypt.password","-Dvalue=someValue");
builder.directory(new File("C:\\ant_builds\\thinclient"));
builder.redirectErrorStream(true);
process = builder.start();
br = new BufferedReader(new InputStreamReader(process.getInputStream(),charset));
pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(log, true), charset));
(new Thread() {
public void run() {
try {
while (process.isAlive()) {
String s = null;
while ((s = br.readLine()) != null) {
pw.print(s);
pw.flush();
}
}
br.close();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
I'm not sure about the order and list of ProcessBuilder arguments so try to play with them to get your code working.
You can also read commands from a common file and redirect output and erros to a sepearate files. Redirect.appendTo is to avoid the process from overiting the existing logs.
Try this code:
try {
File commands = new File("D:/Sample/Commands.txt");
File output = new File("D:/Sample/Output.txt");
File errors = new File("D:/Sample/ErrorsLog.txt");
ProcessBuilder pb = new ProcessBuilder("cmd");
System.out.println(pb.redirectInput());
System.out.println(pb.redirectOutput());
System.out.println(pb.redirectError());
pb.redirectInput(commands);
pb.redirectError(Redirect.appendTo(errors));
pb.redirectOutput(Redirect.appendTo(output));
pb.redirectInput();
pb.redirectOutput();
pb.redirectError();
pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Create a File if it is not already there

In Java we can create a reference to a file by...
File counterFile = new File("countervalue.txt");
but how do we create the file if it does not already exist?
The basic way to create the file would be calling the File#createNewFile method:
File counterFile = new File("countervalue.txt");
try {
counterFile.createNewFile();
} catch (Exception e) {
System.out.println("File couldn't been created.");
}
Now, if you want to create a new File and fill it with data, you can use a FileWriter and a PrintWriter for text files (assuming this for the txt extension in your sample):
File counterFile = new File("countervalue.txt");
PrintWriter pw = null;
try {
//it will automatically create the file
pw = new PrintWriter(new FileWriter(counterFile));
pw.println("Hello world!");
} catch (Exception e) {
System.out.println("File couldn't been created.");
} finally {
if (pw != null) {
pw.flush();
pw.close();
}
}
If you want to just append data to your file, use the FileWriter(File, boolean) constructor passing true as the second parameter:
pw = new PrintWriter(new FileWriter(counterFile, true));
Easily done in java
File counterFile = new File("countervalue.txt");
counterFile.createNewFile();

Categories