Read another software file via java program - java

I'm developing a java program that will read a file, for example; PSD file (example.psd), and I'll edit the bytes of the file. How can I call the adobe software and have it read the edited bytes through the java program without having to write out the file?
package sandbox;
import java.io.IOException;
public class Sandbox {
/**
* Example of how to run an executable from Java.
*
* #param args
*/
public static String readFileAsString(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) {
try {
Runtime runTime = Runtime.getRuntime();
String data = readFileAsString("C:\\Users\\pankaj\\Desktop\\example.psd");
String executablePath = "C:\\Users\\sdkca\\AppData\\Local\\Programs\\Adobe\\Adobe.exe";
Process process = runTime.exec(executablePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can call the adobe, and also read the bytes, how would I tell the adobe to read the bytes?

Take a look here:
Java open file with another program
If there is a default opener for the file in the local OS, then that
Desktop.getDesktop().open(...)
may do the trick

Related

java - opencsv class works perfect individually but doesn't write CSVs when called by another class

I'm using html form to take input of a file and uploading it using doPost() method of HTTPservlet. [This part is done in package one] Now function from class Main.java to parse the uploaded file is called in this doPost method. This function resides in the other package. [Moving to the other package-> ] Here the class Main.java calls Integrated.java which has all the instances of class and functions needed to be called in order to parse the file that was uploaded. (I have separate classes for extracting data, chunking, sorting and generating csv out of the data parsed)
After I parse the file, I put values in variables which are initialized in the last file CSVgenerator.java. Values to these variables are added before in the class SortAndOutput.java. To test that I'm getting the right values in my class, I print the variables right before I call the functions writingDatabase() and writingTraining(). These two functions save the values of the variables in CSV files.
I'm using OpenCSV for writing the files. Using apache Tika for extraction of data and lingpipe to parse.
THE BIG PROBLEM:
I (intentionally) write main func in CSVgenerator.java and test it. Both the files are written properly. The missing value columns are left blank. PERFECT! (If i have any of the CSV open separately, it raises an exception like it should)
But when i comment out the main func and run the whole project together on server, the CSVs are not written. Even if the files are opened separately(outside eclipse), it doesn't give an error.
I have tested the whole integrated Java code by putting a main method in Main.java and it runs perfectly. The problem occurs when servlet is run/I run project on server.
I don't know if other files will be helpful or not, I'm posting the hierarchy and CSVgenerator class
Workspace Screenshot
CSVGenerator.java
package com.fypv1.parser;
import java.io.*;
import java.util.*;
import com.opencsv.*;
public class CSVgenerator {
public static String CGPAinitial="-";
public static String universityNameOut="-";
public static String emailIDOut="-";
public static String phoneNoOut="-";
public static String phpKnow="NO";
public static String databaseKnow="NO";
public static String jsKnow="NO";
public static String bootStrapKnow="NO";
public static String aspKnow="NO";
public static String htmlKnow="NO";
public static String cssKnow="NO";
public static String jqueryKnow="NO";
public static String jspKnow="NO";
public static String reactjsKnow="NO";
public static String ajaxKnow="NO";
public static String oopKnow="NO";
public static String javaKnow="NO";
public static String androidKnow="NO";
private int idNumber;
Writer wr;
Scanner scanner;
/*
* public static void main(String[] args) throws IOException {
new CSVgenerator();
}
*/
//DEFAULT CLASS CONSTRUCTOR
CSVgenerator() throws IOException
{
String trainingCSV = "TrainingData.csv";
String databaseCSV = "databaseInfo.csv";
String idNumberFile = "idnum.txt";
try {
scanner = new Scanner(new File(idNumberFile));
SortAndOutput.applicantIDnumber=scanner.nextInt();
idNumber=SortAndOutput.applicantIDnumber;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("IDnumberFileUnavailable");
}
try {
wr = new FileWriter(idNumberFile);
int newIDNumber=idNumber+1;
wr.write(newIDNumber+"");
wr.close();
} catch (IOException e1) {
//
e1.printStackTrace();
}
//System.out.println( String.valueOf(idNumber)+"+"+universityNameOut+"+"+CGPAinitial+"+"+emailIDOut+"+"+ phoneNoOut+"+"+CGPAinitial+"+"+phpKnow+"+"+ databaseKnow+"+"+ jsKnow+"+"+ bootStrapKnow+"+"+ aspKnow+"+"+ htmlKnow+"+"+ cssKnow+"+"+ jqueryKnow+"+"+ jspKnow+"+"+ reactjsKnow+"+"+ ajaxKnow+"+"+ "?");
writingDatabase(databaseCSV);
writingTraining(trainingCSV);
}//CONSTRUCTOR ENDS
void writingDatabase(String databaseCSV) throws IOException {
CSVWriter dbWriter;
String [] record1={String.valueOf(idNumber),universityNameOut,CGPAinitial,emailIDOut, phoneNoOut };
dbWriter= new CSVWriter(new FileWriter(databaseCSV, true));
dbWriter.writeNext(record1);
dbWriter.close();
}
void writingTraining(String trainingCSV) throws IOException {
CSVWriter trainingWriter;
String [] record={String.valueOf(idNumber),CGPAinitial,phpKnow, databaseKnow, jsKnow, bootStrapKnow, aspKnow, htmlKnow, cssKnow, jqueryKnow, jspKnow, reactjsKnow, ajaxKnow, "?"};
trainingWriter = new CSVWriter(new FileWriter(trainingCSV, true));
trainingWriter.writeNext(record);
trainingWriter.close();
}
}
Integrated.java
ResumeUploadService.java (the servlet)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Part file = request.getPart("file");
resumeFileName = Paths.get(file.getSubmittedFileName()).getFileName().toString();
file.write(path + resumeFileName);
printOnClient(response, "Upload Successful!");
}
catch (Exception e) {
printOnClient(response, "Upload Failed!");
}
new Main(path,resumeFileName);
}
Please let me know if more code is needed to debug this.
It was updating files both times. When it ran on server, it created files in eclipse folder and when i ran as java application, it updated files in project folder
Your files are written in the application folder unless otherwise specified. This is the relative path to the running application.
Just because you tested the application in Eclipse doesn't mean that the server deployment would write to the same folder.
Ideally, you can specify a configuration parameter to your Servlet for an absolute path where files are to be stored

Unix executable changes to TextEdit document when copied

I have the following script, of which you can see below. The function of this Java script is to copy a Mac app, of which is placed in the same folder as the java program. It first finds the path of the folder, which the app and java program is in. It then copies all the content to the documents folder on the Mac device. When that is done it is then supposed to run that app of which it has copied to the documents folder.
The only issue is that it isn't able to do so. The reason being that whenever it copies the app, the JavaAppLauncher which is found within the content of the mac app has changed from a unix executable to a regular TextEdit document and thus can't actually launch the app. However if I were to copy the app manually by copying it myself and not using the java program, there is no issue. I am not sure whether this issue is caused by my code, or whether it is just a general thing?
Important note, the .app does work when I just run the regular non copied version, but as soon as it is the copied version, which as been copied through Java it doesn't work because the change of the Unix executable.
public class LaunchProg {
static String usernameMac2 = System.getProperty("user.name");
static File propFile = new File (".");
static String pathString = propFile.getAbsolutePath();
static int pathhLeng = pathString.length();
static int pathReaLeng = pathhLeng -1;
static String filNamMac = "AppNam.app";
static String pFPathRelMac = pathString.substring(0,pathReaLeng);
private static final File fSourceMac = new File(pFPathRelMac);
private static final File AppFold = new File ("/Users/" + usernameMac2 + "/Documents");
static File fileCret = new File("fCret.txt");
public static void main(String[] args) throws IOException {
System.out.println(pFPathRelMac);
launchMac();
}
static void launchMac() throws IOException {
if (!fileCret.exists()){
try {
FileUtils.copyDirectory(fSourceMac, AppFold);
PrintWriter pFW = new PrintWriter(fileCret);
pFW.println("Created File For Check");
pFW.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
String command = "open /Users/" + usernameMac2 + "/Documents/AppNam.app";
Process staAp2 = Runtime.getRuntime().exec(command);
}
}
}
}

JavaScript to Java Applet using DeployJava.js to run commandline

I am pretty new to Java. I want to create a Java Applet that will allow my JavaScript to pass a commandline to the Java Applet. This will only ever be run on my development machine - no need to remind me what a security issue that is. The use-case is that I have an introspector for my ExtJS app that allows me to display the classes. I want to be able to click a class, pass the relevant pathname to the Applet and have that file open in Eclipse for editing.
I am using Win7x64, jre 1.7
So, to get Eclipse to open the file from the commandline the command is:
D:\Eclipse\eclipse.exe --launcher.openFile C:\mytestfile.js
This works.
I have written the Applet, self signed it and tested the say() method using the code shown below. That works. However when I run the executecmd() method, I don't get any output. If I comment out the whole try/catch block so that I am simply returning the cmd string passed in, the method works. Therefore, I suspect that I have the try catch incorrectly setup and since my Java skills and knowledge of the exceptions are primitive I am lost.
Can anyone help me please? At least to get some output returned, if not how to actually run the command line passed in?
And, I am passing the whole command line because when I have this working I would like to share it (since the Ext introspector is really useful). Other developers will be using different editors so this way they can use it by passing their specific commandline.
Thanks!
Murray
My HTML test page:
<html>
<head>
<meta charset="UTF-8">
<title>Test Run</title>
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = { id:'testapp', code:'systemcmd.Runcmd', archive:'runcmd.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
</head>
<body>
<p>Hello</p>
<script type="text/javascript">
//alert(testapp.say("Hello test")); // This works
var command = "D:\Eclipse\eclipse.exe --launcher.openFile C:\mytestfile.js";
alert(testapp.executecmd(command)); // Nothing returned at all.
</script>
</body>
</html>
My class:
package systemcmd;
import java.applet.Applet;
import java.io.IOException;
import java.security.AccessController;
//import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
public class Runcmd extends Applet {
private static final long serialVersionUID = -4370650602318597069L;
/**
* #param args
*/
public static void main(String[] args) {
}
public String say(String arg)
{
String msg[] = {null};
msg[0] = "In Say. You said: " + arg;
String output ="";
for(String str: msg)
output=output+str;
return output;
}
public String executecmd(final String cmd) throws IOException
{
final String msg[] = {null};
String output ="";
msg[0] = "In executecmd, cmd="+cmd;
try {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public Object run() throws IOException { //RuntimeException,
msg[1] = " Pre exec()";
Runtime.getRuntime().exec(cmd);
msg[2] = " Post exec()";
return null;
}
}
);
} catch (PrivilegedActionException e) {
msg[3] = " Caught PrivilegedActionException:"+ e.toString();
throw (IOException) e.getException();
}
}
catch (Exception e) {
msg[4] = " Command:" + cmd + ". Exception:" + e.toString();
}
msg[5] = " End of executecmd.";
for(String str: msg)
output=output+str;
return output;
}
}
Set Eclipse as the default consumer for .java files and use Desktop.open(File) which..
Launches the associated application to open the file.
Ok, #Andrew. Some progress, thank you!
I set the default program for *.js files to Eclipse and if I double click a file it opens in Eclipse. All good.
I then had success running the following using RunAs Java Application - the test file opened in Eclipse. Getting closer!
public class Runcmd extends Applet {
File file;
private static Desktop desktop;
private static final long serialVersionUID = -4370650602318597069L;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("hello");
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
File file = new File("C:\\sites\\test.js");
// This works if I execute it from the Eclipse RunsAs Java Application.
// ie the file is opened in Eclipse for editing.
// And, if I specify a non-existant file, it correctly throws and prints the error
try {
desktop.open(file);
} catch (Exception ioe) {
ioe.printStackTrace();
System.out.println("Error: " + ioe.toString());
}
}}
However, when I added the following method and ran it via the DeployJava.js (as per my original post above), I get the following output returned with the error appearing whether or not the jar is self signed.
Started: , Desktop is supported , Error:
java.security.AccessControlException: access denied
("java.awt.AWTPermission" "showWindowWithoutWarningBanner")
public static String openfile(String arg) {
String output = "Started: ";
File file = new File("C:\\sites\\test.js");
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
output = output + ", Desktop is supported ";
}
try {
desktop.open(file);
} catch (Exception ioe) {
output = output + ", Error: " + ioe.toString();
}
return output + arg;
}
So, what do I need to add to get around the apparent security issue? I have read the docs and the tutorials and I am going around in circles! There seems to be a lot of conflicting advice. :-(
Thanks again,
Murray

Prevent launching multiple instances of a java application

I want to prevent the user from running my java application multiple times in parallel.
To prevent this, I have created a lock file when am opening the application, and delete the lock file when closing the application.
When the application is running, you can not open an another instance of jar. However, if you kill the application through task manager, the window closing event in the application is not triggered and the lock file is not deleted.
How can I make sure the lock file method works or what other mechanism could I use?
You could use a FileLock, this also works in environments where multiple users share ports:
String userHome = System.getProperty("user.home");
File file = new File(userHome, "my.lock");
try {
FileChannel fc = FileChannel.open(file.toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
FileLock lock = fc.tryLock();
if (lock == null) {
System.out.println("another instance is running");
}
} catch (IOException e) {
throw new Error(e);
}
Also survives Garbage Collection.
The lock is released once your process ends, doesn't matter if regular exit or crash or whatever.
Similar discussion is at
http://www.daniweb.com/software-development/java/threads/83331
Bind a ServerSocket. If it fails to bind then abort the startup. Since a ServerSocket can be bound only once, only single instsances of the program will be able to run.
And before you ask, no. Just because you bind a ServerSocket, does not mean you are open to network traffic. That only comes into effect once the program starts "listening" to the port with accept().
I see two options you can try:
Use a Java shutdown hook
Have your lock file hold the main process number. The process should exist when you lanuch another instance. If it's not found in your system, you can assume that the lock can be dismissed and overwritten.
Creating a server socket, bounds to a specific port with a ServerSocket instance as the application starts is a straight way.
Note that ServerSocket.accept() blocks, so running it in its own thread makes sense to not block the main Thread.
Here is an example with a exception thrown as detected :
public static void main(String[] args) {
assertNoOtherInstanceRunning();
... // application code then
}
public static void assertNoOtherInstanceRunning() {
new Thread(() -> {
try {
new ServerSocket(9000).accept();
} catch (IOException e) {
throw new RuntimeException("the application is probably already started", e);
}
}).start();
}
You could write the process id of the process that created the lock file into the file.
When you encounter an existing lock file, you do not just quit, but you check if the process with that id is still alive. If not, you can go ahead.
You can create a Server socket like
new ServerSocket(65535, 1, InetAddress.getLocalHost());
at very beginning of your code. Then if AddressAlreadyInUse exception caught in main block you can display the appropriate message.
There are already available java methods in File class to achieve the same. The method is deleteOnExit() which ensure the file is automatically deleted when the JVM exits. However, it does not cater to forcible terminations. One should use FileLock in case of forcible termination.
For more details check, https://docs.oracle.com/javase/7/docs/api/java/io/File.html
Thus code snippet which could be used in the main method can be like :
public static void main(String args[]) throws Exception {
File f = new File("checkFile");
if (!f.exists()) {
f.createNewFile();
} else {
System.out.println("App already running" );
return;
}
f.deleteOnExit();
// whatever your app is supposed to do
System.out.println("Blah Blah")
}
..what other mechanism could I use?
If the app. has a GUI it can be launched using Java Web Start. The JNLP API provided to web-start offers the SingleInstanceService. Here is my demo. of the SingleInstanceService.
You can write something like this.
If file exists try to delete it. if it is not able to delete. We can say that application is already running.
Now create the same file again and redirect the sysout and syserr.
This works for me
Simple lock and advanced lock
I developed 2 solutions for this problem. I was also looking for an easy way of doing this without using any libraries and a lot of code.
My solutions are based on: https://stackoverflow.com/a/46705579/10686802 which I have improved upon. Therefore I would like to thank #akshaya pandey and #rbento
Simple file lock
package YOUR_PACKAGE_NAME;
import java.io.File;
import java.io.IOException;
/**
* Minimal reproducible example (MRE) - Example of a simple lock file.
* #author Remzi Cavdar - ict#remzi.info - #Remzi1993
*/
public class Main {
public static void main(String[] args) {
/*
* Prevents the user of starting multiple instances of the application.
* This is done by creating a temporary file in the app directory.
* The temp file should be excluded from git and is called App.lock in this example.
*/
final File FILE = new File("App.lock");
try {
if (FILE.createNewFile()) {
System.out.println("Starting application");
} else {
System.err.println("The application is already running!");
return;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
/*
* Register a shutdown hook to delete the lock file when the application is closed. Even when forcefully closed
* with the task manager. (Tested on Windows 11 with JavaFX 19)
*/
FILE.deleteOnExit();
// Whatever your app is supposed to do
}
}
Advanced lock
package YOUR_PACKAGE_NAME;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
/**
* Minimal reproducible example (MRE) - Example of a more advanced lock system.
* #author Remzi Cavdar - ict#remzi.info - #Remzi1993
*/
public class Main {
public static void main(String[] args) {
/*
* Prevents the user of starting multiple instances of the application.
* This is done by creating a temporary file in the app directory.
* The temp file should be excluded from git and is called App.lock in this example.
*/
final File FILE = new File("App.lock");
if (FILE.exists()) {
System.err.println("The application is already running!");
return;
}
try (
FileOutputStream fileOutputStream = new FileOutputStream(FILE);
FileChannel channel = fileOutputStream.getChannel();
FileLock lock = channel.lock()
) {
System.out.println("Starting application");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
/*
* Register a shutdown hook to delete the lock file when the application is closed. Even when forcefully closed
* with the task manager. (Tested on Windows 11 with JavaFX 19)
*/
FILE.deleteOnExit();
// Whatever your app is supposed to do
}
}
Testing
Tested on: 31-10-2022
Tested OS: Windows 11 - Version 21H2 (OS Build 22000.1098)
Tested with: OpenJDK 19 - Eclipse Temurin JDK with Hotspot 19+36(x64)
I closed the application and also forcefully closed the application with task manager on Windows both times the lock file seems to be deleted upon (force) close.
I struggled with this same problem for a while... none of the ideas presented here worked for me. In all cases, the lock (file, socket or otherwise) did not persist into the 2nd process instance, so the 2nd instance still ran.
So I decided to try an old school approach to simply crate a .pid file with the process id of the first process. Then any 2nd process would quit if it finds the .pid file, and also the process number specified in the file is confirmed to be still running. This approach worked for me.
There is a fair bit of code, which I provide here in full for your use... a complete solution.
package common.environment;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.charset.Charset;
public class SingleAppInstance
{
private static final #Nonnull Logger log = LogManager.getLogger(SingleAppInstance.class.getName());
/**
* Enforces that only a single instance of the given component is running. This
* is resilient to crashes, unexpected reboots and other forceful termination
* scenarios.
*
* #param componentName = Name of this component, for disambiguation with other
* components that may run simultaneously with this one.
* #return = true if the program is the only instance and is allowed to run.
*/
public static boolean isOnlyInstanceOf(#Nonnull String componentName)
{
boolean result = false;
// Make sure the directory exists
String dirPath = getHomePath();
try
{
FileUtil.createDirectories(dirPath);
}
catch (IOException e)
{
throw new RuntimeException(String.format("Unable to create directory: [%s]", dirPath));
}
File pidFile = new File(dirPath, componentName + ".pid");
// Try to read a prior, existing pid from the pid file. Returns null if the file doesn't exist.
String oldPid = FileUtil.readFile(pidFile);
// See if such a process is running.
if (oldPid != null && ProcessChecker.isStillAllive(oldPid))
{
log.error(String.format("An instance of %s is already running", componentName));
}
// If that process isn't running, create a new lock file for the current process.
else
{
// Write current pid to the file.
long thisPid = ProcessHandle.current().pid();
FileUtil.createFile(pidFile.getAbsolutePath(), String.valueOf(thisPid));
// Try to be tidy. Note: This won't happen on exit if forcibly terminated, so we don't depend on it.
pidFile.deleteOnExit();
result = true;
}
return result;
}
public static #Nonnull String getHomePath()
{
// Returns a path like C:/Users/Person/
return System.getProperty("user.home") + "/";
}
}
class ProcessChecker
{
private static final #Nonnull Logger log = LogManager.getLogger(io.cpucoin.core.platform.ProcessChecker.class.getName());
static boolean isStillAllive(#Nonnull String pidStr)
{
String OS = System.getProperty("os.name").toLowerCase();
String command;
if (OS.contains("win"))
{
log.debug("Check alive Windows mode. Pid: [{}]", pidStr);
command = "cmd /c tasklist /FI \"PID eq " + pidStr + "\"";
}
else if (OS.contains("nix") || OS.contains("nux"))
{
log.debug("Check alive Linux/Unix mode. Pid: [{}]", pidStr);
command = "ps -p " + pidStr;
}
else
{
log.warn("Unsupported OS: Check alive for Pid: [{}] return false", pidStr);
return false;
}
return isProcessIdRunning(pidStr, command); // call generic implementation
}
private static boolean isProcessIdRunning(#Nonnull String pid, #Nonnull String command)
{
log.debug("Command [{}]", command);
try
{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
InputStreamReader isReader = new InputStreamReader(pr.getInputStream());
BufferedReader bReader = new BufferedReader(isReader);
String strLine;
while ((strLine = bReader.readLine()) != null)
{
if (strLine.contains(" " + pid + " "))
{
return true;
}
}
return false;
}
catch (Exception ex)
{
log.warn("Got exception using system command [{}].", command, ex);
return true;
}
}
}
class FileUtil
{
static void createDirectories(#Nonnull String dirPath) throws IOException
{
File dir = new File(dirPath);
if (dir.mkdirs()) /* If false, directories already exist so nothing to do. */
{
if (!dir.exists())
{
throw new IOException(String.format("Failed to create directory (access permissions problem?): [%s]", dirPath));
}
}
}
static void createFile(#Nonnull String fullPathToFile, #Nonnull String contents)
{
try (PrintWriter writer = new PrintWriter(fullPathToFile, Charset.defaultCharset()))
{
writer.print(contents);
}
catch (IOException e)
{
throw new RuntimeException(String.format("Unable to create file at %s! %s", fullPathToFile, e.getMessage()), e);
}
}
static #Nullable String readFile(#Nonnull File file)
{
try
{
try (BufferedReader fileReader = new BufferedReader(new FileReader(file)))
{
StringBuilder result = new StringBuilder();
String line;
while ((line = fileReader.readLine()) != null)
{
result.append(line);
if (fileReader.ready())
result.append("\n");
}
return result.toString();
}
}
catch (IOException e)
{
return null;
}
}
}
To use it, simply invoke it like this:
if (!SingleAppInstance.isOnlyInstanceOf("my-component"))
{
// quit
}
I hope you find this helpful.
Finally I found really simple library to achieve this. You can you use JUniqe.
The JUnique library can be used to prevent a user to run at the same
time more instances of the same Java application.
This is an example how to use it from the documentation
public static void main(String[] args) {
String appId = "myapplicationid";
boolean alreadyRunning;
try {
JUnique.acquireLock(appId);
alreadyRunning = false;
} catch (AlreadyLockedException e) {
alreadyRunning = true;
}
if (!alreadyRunning) {
// Start sequence here
}
}
here is a pretty rudimental approach.
If your application is launched from a script, check the running java/javaw processes and their command line before launch
In windows
REM check if there is a javaw process running your.main.class
REM if found, go to the end of the script and skip the launch of a new instance
WMIC path win32_process WHERE "Name='javaw.exe'" get CommandLine 2>nul | findstr your.main.class >nul 2>&1
if %ERRORLEVEL% EQU 0 goto:eof
javaw your.main.class

want to copy a file from a server to a client

i want to copy a file from a server to a client in java.this is my code up to now
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Copy {
private ListDirectory dir = new ListDirectory();
public Copy() {
}
public String getCopyPath(String file) throws Exception {
String path = dir.getCurrentPath();
path += "\\" + file;
return path;
}
public void copyFile(String file) {
try {
File inputFile = new File(dir.getCurrentPath());
URL copyurl;
InputStream outputFile;
copyurl = new URL(getCopyPath(file));
outputFile = copyurl.openStream();
FileOutputStream out = new FileOutputStream(inputFile);
int c;
while ((c = outputFile.read()) != -1)
out.write(c);
outputFile.close();
out.close();
} catch (Exception e) {
System.out.println("Failed to Copy File from server");
e.printStackTrace();
}
}
public static void main(String args[]) {
String a = "put martin";
String b = a.substring(0, 3);
String c = a.substring(4);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Problem is , the server is not uploadded online , but it is on my local drive, and the URL thing doesnt work. is there any other way? is this way correct? thanks
If you're expecting to access your file from the local file system (whether that be via network drive or a local disk), you'll need to treat this as if it is a straight file copy.
If you're expecting to access your file as if it is available for download from an HTTP server, you will need to treat it as an HTTP download (which is what it looks like you're trying to do with the URL).
If you want to test the HTTP download functionality using a file on your local system, just set up a simple HTTP server on your dev machine with a directory on your local system, and give your HTTP-downloading code a URL pointing to that local server (on http://localhost, or using your IP address).
Unfortunately, HTTP is a very different animal from a file system, and I don't think there's any way to use the same code to handle both scenarios. If you want your program to ultimately support both protocols, you should build methods/classes to handle both situations, and then have your program detect and use the appropriate protocol for a given path. You'll need to do the same for any other protocol you wish to support (FTP, SFTP, etc).

Categories