Create executable binaries from Batch or Shell script from Java Programmatically - java

This is not about creating a batch file or executing a batch file from java but creating a binary from them.
I am not very sure about Linux shell scripts but is know that for Windows Batch scripts there are some programs like Batch to Exe Converter. But i want to do it programmatically.
Suppose I read the contents of a batch file from a file :
public static String loadFile(String filepath) {
List<String> lines = Collections.emptyList();
try
{
lines =
Files.readAllLines(Paths.get(filepath), StandardCharsets.UTF_8);
}
catch (IOException e)
{
e.printStackTrace();
}
String s = "";
for(String line:lines){
s += line + "\n"
}
return s;
}
Now i want to convert it to an exe.
Purpose
My main purpose is to create small executables from those scripts for some small automations which will be used instead of the scripts themselves.
For example:-
I have a setup.bat file.
I have my program to automatically generate the batch every time I make any changes(add files) now i also want to have executables along with the scripts.
I also a curious whether a similar thing is possible for Linux shell scripts(creating executables).
Moreover i this is not possible through Java directly can we some how do it using JNI?

Related

Use Java to build an index of files in Windows 10

I am writing a desktop application in Java to quickly find files. I have used the exec command in Java to run powershell to do this, as Java's os.walk method seems to be much slower. Right now it takes about 5 minutes to generate a text file that lists the contents of all files on my computer (a total of around 440,000 files).
This is fine, but the problem I have is that I have no way of updating this list of files. So if I change a few files in my file system and want to update my file list, I can't do so quickly (i.e. incrementally). Instead, I have to generate the file list all over from scratch.
I know you can use git-bash to create a locate database (using updatedb). Now this is an awesome solution, but the application I'm trying to create may be used by people who don't have that installed. So I'd like to do it using default apps provided with Windows (i.e. powershell, or natively in Java). I am trying to make this app easy to use, so I don't want the user to have to install a bunch of other dependencies.
The following code shows how to use Java and avoid Powershell altogether. It builds an array in memory and writes it to a text file (467,000 files listed) all in under 30 seconds!
Run the following code in Main or wherever you want. It calls the createFileList method.
List<Path> pathsArrayList = new ArrayList<>();
Path rootPath_obj;
rootPath_obj = Paths.get(this.configMap.get("root_path"));
createFileList(rootPath_obj);
Here's the tree stream traversal code:
public void createFileList(Path path_in) throws IOException, AccessDeniedException {
try (DirectoryStream<Path> mystream = Files.newDirectoryStream(path_in)) {
for (Path entry : mystream) {
if (Files.isDirectory(entry)) {
createFileList(entry);
}
pathsArrayList.add(entry);
}
}
catch (AccessDeniedException ex) {
// Do nothing, just move on to the next file
}
}
Now write the file to save for later. This is the listing of all files within the root path tree.
System.out.println("Writing database...");
try (FileWriter writer = new FileWriter(this.configMap.get("db_path"))) {
for(Path pth: pathsArrayList){
writer.write(pth.toString() + System.lineSeparator());
}
}
System.out.println("...database written.");

Copy data from one csv file to another csv file using java

I'm working on a Java code to copy the data from one csv file into another csv file .
The requirement is that files (multiple files) that are uploaded in a particular path has to be copied one at a time into another csv file(say tag.csv) in a different location.Later tag.csv will be picked up by a shell script and connect to Oracle DB to run a stored procedure .All of this is done repeatedly until all the uploaded files is processed and shell script is triggered for each file separately.
Now I'm in stuck in copying the csv data .
I have tried using buffered reader,filewriter etc. but i'm unable to copy the data to tag.csv,but I could just read them .
Since Im new to java im finding it hard to understand where im going wrong.
Help is much appreciated.
You can simply use the Java 7 NIO2:Eg:
If you want to copy a file from one location to another, simply call:
Files.copy(fromPath, toPath);
If you want to move:
Files.move(fromPath, toPath);
With Java 7 features, you don't need to write hard code for files handling. Hope it help.
Java 7 NIO2 Tutorial Link
Edited:
But your requirement is not file copy but you want to write uploaded file contents to existing file, you can also simply use the Java 7 NIO2 features.
Eg:
private static void writeFileAsAppend() throws IOException {
List<String> lines = readFileAsSequencesOfLines();
Path path = getWriteFilePath();
Files.write(path, lines, StandardOpenOption.APPEND);
}
private static List<String> readFileAsSequencesOfLines() throws IOException {
Path path = getReadFilePath();
List<String> lines = Files.readAllLines(path);
return lines;
}
private static Path getReadFilePath() {
Path path = Paths
.get(".\\ReadMe.csv");
return path.normalize();
}
private static Path getWriteFilePath() {
Path path = Paths
.get(".\\WriteMe.csv");
return path;
}

How to compile and run MULTIPLE java programs from another java program without knowing their class names?

Assume there is a zip file containing 4-5 simple java programs. I want to write a code that unzips the file(this part is easy), compiles and runs all the .java files in it.
So far I have been able to compile and run individual java programs using another java program, although I have to know their class names. What if I only know the directory where they are located but not their names?
Normally to run any program, you need to know the name of the program that you will execute.
Now, if "all" the classes on your zip file will be run, then you can:
Unzip the files.
Read all the files names (classes) and put
them in a String[].
Parse the String[] and execute each name
(class) on the array as a class; you may need Reflection enter link
description here.
Let me know if you need more help.
Try something like this:
File directory = new File("c:\temp");
File[] files = directory.listFiles();
for (File thisClass : files) {
Runtime runTime = Runtime.getRuntime();
try {
Process process = runTime.exec(thisClass.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Java open live file at runtime

I have a table of data and i wanted an export function, this application run on web so i want to create a csv file and then offer (open or save as option) usual download options. Im using CSV writer at the moment.
The line in question here is Runtime.getRuntime().exec("export.csv"); give error listed at bottom
How would i do this?
Here is the action tied to a button
Action exportData = new Action() {
private static final long serialVersionUID = -7803023178172634837L;
#Override
public void execute(UIContext uic, ActionEvent event) {
try{
CSVWriter writer = new CSVWriter(new FileWriter("export.csv"), '\t');
int i = 0;
while (i < forExport.getTotalCount()){
String[] entries = {
forExport.getSearchResults().get(i).getName().getGivenNames() + forExport.getSearchResults().get(i).getName().getSurname(),
forExport.getSearchResults().get(i).getId()
};
writer.writeNext(entries);
i++;
}
writer.close();
Runtime.getRuntime().exec("export.csv");
}catch(Exception e){
system.out.print(e);
}
}
};
getting error java.io.IOException: Cannot run program "export.csv": CreateProcess error=193, %1 is not a valid Win32 applicationDEBUG
NOTE: i do not want it to automatically open in excel, i want the option to save or open.
I don't understand why you are exec-ing anything whatsoever. This is server code. You don't want to exec Excel at the server at all. You want to write the file back to the browser, along with a content-disposition header.
You should try
Runtime.getRuntime().exec("excel.exe export.csv");
export.csv is not a valid windows command.
A .csv file is a comma separated value file which is used to keep data. and the parameter of the exec command is the command as string to open the .csv file. But in your command string you have not specified any program with which the runtime should try to open the .csv file.
As a .csv file is not executable, In the command string parameter specify the program name with ahich you want to open the ..csv file.

zip folder in windows using command line

I am writing a program that needs to zip a file.
This will run over both linux and windows machines. It works just fine in Linux but I am not able to get anything done in windows.
To send commands I am using the apache-net project. I've also tried using Runtime().exec
but it isn't working.
Can somebody suggest something?
CommandLine cmdLine = new CommandLine("zip");
cmdLine.addArgument("-r");
cmdLine.addArgument("documents.zip");
cmdLine.addArgument("documents");
DefaultExecutor exec = new DefaultExecutor();
ExecuteWatchdog dog = new ExecuteWatchdog(60*1000);
exec.setWorkingDirectory(new File("."));
exec.setWatchdog(dog);
int check =-1;
try {
check = exec.execute(cmdLine);
} catch (ExecuteException e) {
} catch (IOException e) {
}
Java provides its own compression library in java.util.zip.* that supports the .zip format. An example that zips a folder can be found here. Here's a quickie example that works on a single file. The benefit of going with native Java is that it will work on multiple operating systems and is not dependent on having specific binaries installed.
public static void zip(String origFileName) {
try {
String zipName=origFileName + ".zip";
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipName)));
byte[] data = new byte[1000];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(origFileName));
int count;
out.putNextEntry(new ZipEntry(origFileName));
while((count = in.read(data,0,1000)) != -1) {
out.write(data, 0, count);
}
in.close();
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
The same code won't work in Windows. Windows doesn't have a "zip" program the way that Linux does. You will need to see if Windows 7 has a command line zip program (I don't think it does; see here: http://answers.microsoft.com/en-us/windows/forum/windows_vista-files/how-to-compress-a-folder-from-command-prompt/02f93b08-bebc-4c9d-b2bb-907a2184c8d5). You will likely need to do two things
Make sure the user has a suitable 3rd party zip program
Do OS detection to execute the proper command.
You can use inbuilt compact.exe to compress/uncompress in dos
It displays or alters the compression of files on NTFS partitions.
COMPACT [/C | /U] [/S[:dir]] [/A] [/I] [/F] [/Q] [filename [...]]
/C Compresses the specified files. Directories will be marked so that files added afterward will be compressed.
/U Uncompresses the specified files. Directories will be marked so that files added afterward will not be compressed.
/S Performs the specified operation on files in the given directory and all subdirectories. Default "dir" is the current directory.
/A Displays files with the hidden or system attributes. These files are omitted by default.
/I Continues performing the specified operation even after errors have occurred. By default, COMPACT stops when an error is encountered.
/F Forces the compress operation on all specified files, even those that are already compressed. Already-compressed files are skipped by default.
/Q Reports only the most essential information.
filename Specifies a pattern, file, or directory.
Used without parameters, COMPACT displays the compression state of the current directory and any files it contains. You may use multiple filenames and wildcards. You must put spaces between multiple parameters.
Examples
compact
Display all the files in the current directory and their compact status.
compact file.txt
Display the compact status of the file file.txt
compact file.txt /C
Compacts the file.txt file.

Categories