How to run the Linux "cd" command from Java? - java

I want to write a Java program to delete ~12 directories or files which are under my home directory. I am able to do this by using
Process proc = Runtime.getRuntime().exec("rm -rf *path*")
But I have to run this command 12 times or I can keep it in loop. What I really want is to have a file in my home directory that contains the names of all the directories and files to delete in it. My Java program should go to the home directory, read the file, and delete all the specified files.
I am stuck at the very first step – I am not able to cd to the home directory. Please let me know how can I achieve this.
Thanks for all of your replies.
But, here I don't really want to use the Java util classes rather I want to learn a way using which I can run Linux commands in my Java class. Being a deployment Intern, I have to reset the environment every time before deploying a new environment for the customer. For this, I repeatedly use some basic Linux commands. I can write a shell script to do this but for this time, I want to write a Java class in which I can put all these Linux commands and run from one class.
The commands which I use are:
kill all java processes which are started by the admin ONLY – for this I need to use multiple Linux commands with “pipe”
Remove all 12-directories/files from home directory
stop some services (like siebel, etc.) – for this I need to go under the particular directories and run ./shutdown.sh or ./stop_ns, etc.
run some database scripts – to reset the database schemas
again start the services – same as step 2 except this time I need to run ./start_ns, etc.
I really appreciate if you can let me know
a. How can I navigate into a directory using Java code
b. How can I run multiple Linux commands using pipe using Java code

Why do you need to "go" to the home directory? Just read the file wherever you are:
String homeDirectory = System.getProperty("user.home");
File file = new File(homeDirectory, "filenames.txt"); // Or whatever
// Now load the file using "file" in the constructor call to FileInputStream etc
It's very rarely a good idea to require that a process changes working directory just to do the right thing.

You dont need to change directory. You can just read file using absolute path using FileReader(String fileName).

For deleting entire directories, try Apache Commons IO's class FileUtils:
FileUtils.deleteDirectory(new File(System.getProperty("user.home")));
Or use cleanDirectory to delete everything in home but not home itself:
FileUtils.cleanDirectory(new File(System.getProperty("user.home")));
If you want to delete specific files only (e.g. those matching a name pattern), list the files first, then delete them:
File startDir = new File(System.getProperty("user.home"));
//this should return the leaf files first, then the inner nodes of the directory tree
Collection<File> files = FileUtils.listFiles(startDir , someFileFiler, someDirFilter);
for(File f : files) {
f.delete();
}

"cd" is a shell internal command, not a executable program.
Even you can change dir in java program by whatever means like JNA, when it exit, the current dir in shell is not changed, because the java program runs in another process than the shell.
But we still can do something about it.
eg. I want to make a new shell command called xcd, it popup a GUI shows a list let you select directories existed in bash history, and change current dir to it for you.
in ~/.bashrc add a line:
xcd(){
XCDRES=`xcd.sh`
if [ "$XCDRES" ]; then
cd "$XCDRES"
fi
}
2.xcd.sh is
#!/bin/bash
java -cp $PATH1/xcd.jar neoe.xcd.Main
and add xcd.sh to PATH
the java program is
package neoe.xcd;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Main {
public static String getUserHomeDir() {
return System.getProperty("user.home");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
public static String readString(InputStream ins, String enc) throws IOException {
if (enc == null)
enc = "UTF-8";
BufferedReader in = new BufferedReader(new InputStreamReader(ins, enc));
char[] buf = new char[1000];
int len;
StringBuffer sb = new StringBuffer();
while ((len = in.read(buf)) > 0) {
sb.append(buf, 0, len);
}
in.close();
return sb.toString();
}
private String[] selection = new String[1];
private void run() throws Exception {
File hisfile = new File(getUserHomeDir(), ".bash_history");
if (!hisfile.exists()) {
System.err.println(".bash_history not exists, quit");
return;
}
String[] ss = readString(new FileInputStream(hisfile), null).split("\n");
List<String> res = new ArrayList<String>();
Set uniq = new HashSet();
for (String s : ss) {
s = s.trim();
if (!s.startsWith("cd /")) {
continue;
}
s = s.substring(3);
File f = new File(s);
if (f.isDirectory()) {
s = f.getAbsolutePath();
if (uniq.contains(s)) {
continue;
}
uniq.add(s);
res.add(s);
}
}
if (res.isEmpty()) {
System.err.println("no cd entry, quit");
return;
}
Collections.sort(res);
String cd1 = selectFromList(res);
if (cd1 == null) {
System.err.println("not selected, quit");
return;
}
doCd(cd1);
}
private void doCd(String cd1) throws Exception {
System.out.println(cd1);
}
private String selectFromList(List<String> res) {
final JList list = new JList(res.toArray());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JDialog frame = wrapFrame(new JScrollPane(list), "select dir to cd");
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
String s = (String) list.getSelectedValue();
selection[0] = s;
frame.dispose();
}
}
});
list.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
if (kc == KeyEvent.VK_ESCAPE) {
frame.dispose();
} else if (kc == KeyEvent.VK_ENTER) {
String s = (String) list.getSelectedValue();
selection[0] = s;
frame.dispose();
}
}
});
frame.setVisible(true);
frame.requestFocus();
return selection[0];
}
private JDialog wrapFrame(JComponent comp, String title) {
JDialog frame = new JDialog();
frame.setTitle("select dir to cd");
frame.setModal(true);
frame.add(comp);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(400, 600);
frame.setLocationRelativeTo(null);
return frame;
}
}
use xcd in shell.

You can't really do that. Java programs don't really allow you to change the "current working directory" as most people understand it (not without using native code, anyway). The normal Java approach is to open a File instance on the directory you want to manipulate, and then use operations on that instance to manipulate the files/directories in question.
For details on how to delete directories programatically in Java, see: Delete directories recursively in Java

Related

JavaFX app overwriting files while being open causes exception

I have a runnable jar file (with a lib folder housing all the dependency jars). This is located on a network share which anyone that has access can run from. This works great except one huge caveat. If I want to deploy a new version of the software, I have to ask everyone to exit the application first. This is because if I overwrite the jars with new versions (or if there is a network blip), the running program stays open but as soon as they do an action that requires code in of the dependencies (jar file in lib folder), it will cause an exception:
Exception in thread "JavaFX Application Thread" java.lang.NoClassDefFoundError
The program will not produce an error, but certain actions will break, like communicating with an API etc.
Is there a way that I can resolve this so that I can publish updates while the user's are working or at least produce a prompt that will force them to close/and reopen the app etc.
One approach:
Provide a script which launches the application from a local copy of the remote code.
Store a version number with your app.
The script checks if there is a local copy of the app on the machine.
If no local version exists, the script copies the jars from your network share to a local copy.
If there is already a local copy, it checks the version against the network version.
If the network version is updated, it overwrites the local copy with the new remote version before launching the app,
otherwise it just launches the local copy.
If you want the users to be alerted that they are currently running an outdated copy, you could create a JavaFX task which polls the remote version number and checks it against the currently running version number. If they differ, you can alert and (if you wish) shutdown the app and re-trigger the launcher script.
I was able to create a scheme in which I have multiple server folder locations that house the jar distributable. And this jar basically checks these locations for the latest copy of the application and runs that latest copy. I was able to get it working for both Mac and Windows (didn't test Linux) by detecting the OS.
So now, I can publish an update over the oldest app, and the next time the user opens the app, it will be the latest copy.
process.properties
location.a=Application/A
location.b=Application/B
app=app.jar
You can add folders A-Z but just add them into the properties.
Main.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
public class Main
{
public static Properties properties;
private static final String DEFAULT_PROPERTY_FILE_LOCATION = Paths.get("").toAbsolutePath().toString() + File.separator + "process.properties";
private static final String JAVE_EXEC;
static
{
String os = System.getProperty("os.name");
if (StringUtils.containsIgnoreCase(os, "win"))
{
JAVA_EXEC = "java";
} else if (StringUtils.containsIgnoreCase(os, "mac"))
{
JAVA_EXEC = "/usr/bin/java";
} else if (StringUtils.containsIgnoreCase(os, "nux") || StringUtils.containsIgnoreCase(os, "nix"))
{
JAVA_EXEC = "/usr/bin/java";
} else
{
JAVA_EXEC = "java";
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Main.properties = new Properties();
try
{
InputStream in = new FileInputStream(DEFAULT_PROPERTY_FILE_LOCATION);
Main.properties.load(in);
System.out.println("Loaded property file: " + DEFAULT_PROPERTY_FILE_LOCATION);
TreeMap<Long, String> locations = new TreeMap<>();
String appName = Main.properties.getProperty("app");
if (validateProperties(properties))
{
for (int letter = 'a'; letter <= 'z'; ++letter)
{
String location = "location." + (char) letter;
if (Main.properties.getProperty(location) != null)
{
String networkLocation = Paths.get("").toAbsolutePath() + File.separator + Main.properties.getProperty(location);
File file = new File(networkLocation + File.separator + appName);
if (file.exists())
{
locations.put(FileUtils.lastModified(file), networkLocation);
}
}
}
if (!locations.isEmpty())
{
Runtime.getRuntime().exec(new String[]
{
JAVA_EXEC, "-jar", locations.lastEntry().getValue() + File.separator + appName
}, null, new File(locations.lastEntry().getValue()));
}
}
} catch (IOException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static boolean validateProperties(Properties properties)
{
List<String> mandatoryProperties = new ArrayList<>();
mandatoryProperties.add("app");
for (String mandatoryProperty : mandatoryProperties)
{
if (properties.get(mandatoryProperty) == null)
{
System.out.println("Failed - Property: " + mandatoryProperty + " doesn't exist.");
return false;
}
}
return true;
}
}

Java, after using FileDialog, compilation does not end

I have simple java code to select the file and return array.
When I use dedicated method (whole code below), my compilation (in IntelliJ) does not end -> it gets to the last lane of public static void main(String[] arg), it executes last lane System.out.println("Program ends."); but I don't get information from compilator:
Process finished with exit code -1
Instead I need to stop it manually and if I want to run it again I get information that I can't run the code in parallel, would I like to stop it and rerun now.
Whole code:
import java.util.HashMap; //import the HashMap class
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import java.awt.FileDialog;
import java.awt.Frame;
public class Project1
{
public static void main(String[] arg)
{
HashMap<Integer, int[][]> dicUsedFuncs = new HashMap<Integer, int[][]>();
//import textfile with haskell code
String[] arrString=SelectFile();
System.out.println(arrString[0]);
System.out.println(arrString[1]);
//scan load
System.out.println("End");
}
private static String[] SelectFile()
{
String[] arrReturn = new String[2];
String strDefaultPath=System.getProperty("user.dir"); //default location to open
Frame frame = null;
FileDialog fd = new FileDialog(frame, "Please choose a text file with code.", FileDialog.LOAD);
fd.setDirectory(strDefaultPath);
fd.setFile("*.txt");
fd.setVisible(true);
String filename = fd.getFile(); //get just the selected file name
if (filename == null) {
arrReturn[0] = "NotSelected";
}else {
filename= new File(fd.getFile()).getAbsolutePath(); //get full file path of selected file
arrReturn[0] = "Selected";
arrReturn[1] = filename;
}
return arrReturn;
}
}
I added following:
library
import java.awt.Window;
loop to close all windows in method private static String[] SelectFile()
for (Window window : Window.getWindows()) { window.dispose(); }

create .gitignore with java

I'm aware this question might be a duplicate in some sense but first hear me out.
I tried to create a code where i can create gitignore file with contents and for some reason i always end up having a file with txt extension and without name. Can someone explain this behavior and why?
Example Code:
System.out.println(fileDir+"\\"+".gitignore");
FileOutputStream outputStream = new FileOutputStream(fileDir+"\\"+".gitignore",false);
byte[] strToBytes = fileContent.getBytes();
outputStream.write(strToBytes);
outputStream.close();
You can use java.nio for it. See the following example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class StackoverflowMain {
public static void main(String[] args) {
// create the values for a folder and the file name as Strings
String folder = "Y:\\our\\destination\\folder"; // <-- CHANGE THIS ONE TO YOUR FOLDER
String gitignore = ".gitignore";
// create Paths from the Strings, the gitignorePath is the full path for the file
Path folderPath = Paths.get(folder);
Path gitignorPath = folderPath.resolve(gitignore);
// create some content to be written to .gitignore
List<String> lines = new ArrayList<>();
lines.add("# folders to be ignored");
lines.add("**/logs");
lines.add("**/classpath");
try {
// write the file along with its content
Files.write(gitignorPath, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It creates the file on my Windows 10 machine without any problems. You need Java 7 or higher for it.

how can import ms.security package

I am beginner in java.
I want run native application from applet.
I found Run App In Every Browser
Java Code
import com.ms.security.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.* ;
import java.util.*;
import netscape.security.PrivilegeManager;
public class RunApp extends Applet implements ActionListener {
TextArea ta = new TextArea (25, 80);
Button startbutton = new Button("Start Application") ;
private static String execommand = "C:\\windows\\notepad.exe" ;
private String osname;
public void init() {
try {
if (Class.forName("com.ms.security.PolicyEngine") != null) { // required for IE
PolicyEngine.assertPermission(PermissionID.SYSTEM);
}
}
catch (Throwable cnfe) {
}
this.setBackground(Color.white) ;
startbutton.addActionListener(this) ;
add(startbutton) ;
startbutton.setBackground(Color.red) ;
try{
PrivilegeManager.enablePrivilege("UniversalExecAccess") ; // required for NN
}
catch(Exception cnfe) {
System.out.println("netscape.security.PrivilegeManager class not found") ;
}
osname = System.getProperty("os.name"); // if NT, Win2000 or WinXP, adjust path
if(osname.equals("Windows NT") || osname.equals("Windows 2000")|| osname.equals("Windows XP"))
execommand = "C:\\winnt\\notepad.exe" ;
}
public void actionPerformed(ActionEvent e) {
if( (e.getActionCommand()).equals("Start Application")) {
try{
PrivilegeManager.enablePrivilege("UniversalExecAccess") ; // required for NN
}
catch(Exception cnfe) {
System.out.println("netscape.security.PrivilegeManager class not found") ;
}
try {
Process proc = Runtime.getRuntime().exec(execommand) ;
}
catch(IOException ieo) {
System.out.println("Problem starting " + execommand) ;
}
// System.out.println("execommand: " + execommand) ;
}
}
}
But when run it say error:package com.ms.security does not exit!
I does not any folder with ms or security name .
I should create folder with ms and then security in root file or should import library ms.security .
where is com.ms.security or netscape.security.PrivilegeManager?
how can download it?i search for download this package but i does not found anythings
I use eclipse for write code.
This package does not exist any more. The tutorial you point to dates from 2002. You can look at this javaranch post: http://www.coderanch.com/t/375470/java/java/Location-Jar-ms-security, and at the Microsoft documentation (https://msdn.microsoft.com/en-us/library/aa242534(v=vs.60).aspx). So basically your code would have worked 13 years ago, but with Microsoft not supporting their own JVM any more it's obsolete. Sorry!
You need to download that jar having this package ,com.ms.security. And b4 compiling your java class set that jar in your classpath from command prompt.
set classpath=%classpath%;path_of_your_jar;
This package is not existed anymore. Microsoft is not supporting their own JVM anymore. You should try to learn java applet in the new way, such as http://www.tutorialspoint.com/java/java_applet_basics.htm.
The import statement import com.ms.security.*; requires you to have a folder com, with a subfolder ms, with a subfolder security, which contains the needed files.
I think you are missing some files for your application.
I recommend reading this post, for the use of imports: https://stackoverflow.com/a/12620773/3234981
Please check your jar file which contain the respective package are present in the classpath or not. If not, push them to classpath and re-compile the same class on a new command line.
Happy Learning.

Directory Reader Applet Loads in Eclipse, but not in Browser

I'm fairly new to programming and I just wrote an applet program that is supposed to list the files in a directory. The applet works well in eclipse, yet the issue is when I attempt to run the applet in a browser the GUI loads, yet the applet will not respond as it does in eclipse. Any help would be greatly appreciated. :)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JApplet;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class DirReader extends JApplet{
private JTextArea outputWindow;
private JTextField dirPath;
private String path;
private Font font;
private File folder;
private File[] listOfFiles;
public void init(){
font = new Font("Times New Roman", Font.PLAIN, 16);
dirPath = new JTextField("Enter Directory Path");
dirPath.setFont(font);
outputWindow = new JTextArea();
outputWindow.setEditable(false);
outputWindow.setFont(font);
outputWindow.setBackground(Color.DARK_GRAY);
outputWindow.setForeground(Color.ORANGE);
add(dirPath, BorderLayout.NORTH);
add(outputWindow, BorderLayout.CENTER);
setSize(400,750);
dirPath.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event) {
path = dirPath.getText();
folder = new File(path);
listOfFiles = folder.listFiles();
System.out.println("Directory path set");
ListOfFiles();
}
}
);
System.out.println("Progam Intilized:");
}
public void ListOfFiles(){
outputWindow.setText(null);
try{
for(int counter = 0 ; counter < listOfFiles.length ; counter++ ){
if(listOfFiles[counter].isFile()){
outputWindow.append("[FILE] " + listOfFiles[counter].getName()+ "\n");
System.out.println("[FILE] " + listOfFiles[counter].getName());
}
else if(listOfFiles[counter].isDirectory()){
outputWindow.append("[DIR] " + listOfFiles[counter].getName() + "\n");
System.out.println("[DIR] " + listOfFiles[counter].getName());
}
}
}catch(Exception e){
System.out.println("Error: Directory could not be found.");
outputWindow.setText("Error: Could not find directory.");
}
}
}
Of course it does NOT work in browser
Because
when applet run in a browser as a security precaution there is no access to read files on the local file system.
Solution
Make your program as a Desktop application run in desktop NOT Applet run in browser
An untrusted applet cannot get a directory listing
A trusted applet cannot get a directory listing on the server (only the client).
For an applet to gain a file listing on the server, it will need to be explicitly told what the files are. Two common ways are:
Add the file list as parameters for the applet.
Have the applet access server side functionality to get a file listing.
BTW:
}catch(Exception e){
Should become..
}catch(Exception e){
e.printStackTrace(); //...
Be sure to figure out how to access the Java Console to see the output. Debugging applets without that information is like trying to debug wearing a blind-fold.

Categories

Resources