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(); }
Related
Does anyone know a repo that shows what a simple HelloWorld java or scala code would look like to build the jar that could be executed using the AWS SageMaker SparkJarProcessing class?
Readthedocs (https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_processing/spark_distributed_data_processing/sagemaker-spark-processing.html) mentions:
"In the next example, you’ll take a Spark application jar (located in ./code/spark-test-app.jar)..."
My question is how does the source code look like for this jar (spark-test-app.jar)?
I tried building a simple Java project jar
src>com.test>HW.java:
public class HW {
public static void main(String[] args) {
System.out.printf("hello world!");
}
}
and running it inside SageMaker Notebook conda_python3 kernel using
from sagemaker.spark.processing import SparkJarProcessor
from sagemaker import get_execution_role
role = get_execution_role()
print(role)
spark_processor = SparkJarProcessor(
base_job_name="sm-spark-java",
framework_version="3.1",
role=role,
instance_count=2,
instance_type="ml.m5.xlarge",
max_runtime_in_seconds=1200,
)
spark_processor.run(
submit_app="./SparkJarProcessing-1.0-SNAPSHOT.jar",
submit_class="com.test.HW",
arguments=["--input", "abc"],
logs=True,
)
But end up getting an error:
Could not execute HW class.
Any sample source code for spark-test-app.jar would be highly appreciated!
To answer your question, the source code of that class looks like:
package com.amazonaws.sagemaker.spark.test;
import java.lang.invoke.SerializedLambda;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.spark.sql.Dataset;
import org.apache.commons.cli.CommandLine;
import org.apache.spark.sql.types.DataTypes;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import org.apache.spark.sql.SparkSession;
public class HelloJavaSparkApp
{
public static void main(final String[] args) {
System.out.println("Hello World, this is Java-Spark!");
final CommandLine parsedArgs = parseArgs(args);
final String inputPath = parsedArgs.getOptionValue("input");
final String outputPath = parsedArgs.getOptionValue("output");
final SparkSession spark = SparkSession.builder().appName("Hello Spark App").getOrCreate();
System.out.println("Got a Spark session with version: " + spark.version());
System.out.println("Reading input from: " + inputPath);
final Dataset salesDF = spark.read().json(inputPath);
salesDF.printSchema();
salesDF.createOrReplaceTempView("sales");
final Dataset topDF = spark.sql("SELECT date, sale FROM sales WHERE sale > 750 SORT BY sale DESC");
topDF.show();
final Dataset avgDF = salesDF.groupBy("date", new String[0]).avg(new String[0]).orderBy("date", new String[0]);
System.out.println("Collected average sales: " + StringUtils.join((Object[])new List[] { avgDF.collectAsList() }));
spark.sqlContext().udf().register("double", n -> n + n, DataTypes.LongType);
final Dataset saleDoubleDF = salesDF.selectExpr(new String[] { "date", "sale", "double(sale) as sale_double" }).orderBy("date", new String[] { "sale" });
saleDoubleDF.show();
System.out.println("Writing output to: " + outputPath);
saleDoubleDF.coalesce(1).write().json(outputPath);
spark.stop();
}
private static CommandLine parseArgs(final String[] args) {
final Options options = new Options();
final CommandLineParser parser = (CommandLineParser)new BasicParser();
final Option input = new Option("i", "input", true, "input path");
input.setRequired(true);
options.addOption(input);
final Option output = new Option("o", "output", true, "output path");
output.setRequired(true);
options.addOption(output);
try {
return parser.parse(options, args);
}
catch (ParseException e) {
new HelpFormatter().printHelp("HelloScalaSparkApp --input /opt/ml/input/foo --output /opt/ml/output/bar", options);
throw new RuntimeException((Throwable)e);
}
}
}
At the same time, I have created a simple example that shows how to run an hello world app here. Please note that I have run that example on Amazon SageMaker Studio Notebooks, using the Data Science 1.0 kernel.
Hope this helps.
I am trying to make a game with LibGDX, and am having some problems with a certain class (WorldGen.java). Every time I try to run the code normally, I get a black screen that says it is Not Responding when clicked, and there appear to be no errors. The program runs fine when any references to the methods in WorldGen.java are commented out. This seemed to work fine previously, and I have only changed the if statement in this class since then.
This code is intended to create an array of Strings, convert that to a List, and then print that to a txt file.
package com.mygdx.rpg;
import java.io.IOException;
import java.nio.charset.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WorldGen {
static List<String> printString = new ArrayList<String>();
static String username = System.getProperty("user.name");
static String mapData;
static Path mapSavePath = Paths.get("C:\\Users\\"+username+"\\Desktop\\MapFile.txt");
static Charset utf8 = StandardCharsets.UTF_8;
static String[] map = new String[1000000]; //right = +1, down = +100
//problem with generate class, causes black screen and Not Responding to occur
public static void generate(){
for(int i=0;i<1000000;i++){ //1000 x 1000 tiles, encompasses ALL world generation
if(i>-1 && i<1001 || i>999000 && i<1000001){
map[i]="-"; //void (top/bottom edges, must add to all tiles bordering edges of map)
}else if(i%1000==0){
map[i]="-"; //adds void to multiples of 1000 & 999+multiples of 1000 (left/right edges)
map[i-1]="-";
}else{
map[i]="G"; //grass
}
mapData = Arrays.toString(map);
mapData = mapData.replaceAll("\\[","").replaceAll("\\]","").replaceAll(",","");
printString.add(mapData);
}
}
public static void writeToFile(){
try{
Files.write(mapSavePath,printString,utf8);
}catch(IOException e){e.printStackTrace();}
}
I am trying to make a program that uses JFrames and JPanels to construct a voting program. There is a file called voters.txt that is formatted like so:
1234:Herb Weaselman:false
9876:Marge Magnificent:false
4444:Ingmar Inglenook:false
8888:Hector Heroman:false
5678:Agnes Angular:false
In the beginning of my program, I have to ask the user for their voter ID and if their input does not match one of the IDs from the text file, then the program ends. I have managed to achieve this but now I need to overwrite this voters.txt file by changing the false element of whoever voted to true. For instance, if the user entered an ID of 1234, then I would need to change the word after Herb Weaselman to true instead of false. I am not sure how to do this. I know how to write to a file but am not sure how to change that one specific element. Here is the code I have currently:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Assig5 extends JFrame
{
public Assig5()
{
}
public static void main(String[] args) throws IOException
{
LoginWindow loginWindow = new LoginWindow();
loginWindow.fileReader();
if(!loginWindow.checkResult(loginWindow.result))
{
System.out.println("Invalid Voter ID");
System.exit(0);
}
System.out.println("Continue");
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class LoginWindow extends JFrame
{
static ArrayList<String> list = new ArrayList<String>();
public String result;
public LoginWindow()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
result = JOptionPane.showInputDialog(frame, "Enter voter ID:");
}
public static void fileReader() throws FileNotFoundException
{
Scanner s = new Scanner(new File("voters.txt"));
while (s.hasNextLine())
{
list.add(s.nextLine());
}
s.close();
}
public static boolean checkResult(String result)
{
for(int i = 0; i < list.size(); i++)
{
String[] retval = list.get(i).split(":");
if(retval[0].equals(result))
{
return true;
}
}
return false;
}
}
Any help would be appreciated. Thanks in advance.
Just change your array index from false to true when there is a match. Then rewrite the file with the data from the array. If there is not match, the file does not change.
Solution
if(retval[0].equals(result)){
retval[2] = true;
return true;
}
Sorry about readability. Stack appears to be trimming spaces from code lines & indents don't show up. Hrmph.
This was printing to the console without any problems...
CGT\whgdata\whnvp33.txt << EXPECTED OUTPUT (excerpt)
CGT\whgdata\whnvt30.txt
CGT\whgdata\whnvt31.txt
CGT\whgdata\whnvt32.txt
CGT\whgdata\whnvt33.txt
CGT\whgdef.txt
CGT\whgdhtml.txt
CGT\whibody.txt
etc....
...until I tried printing the hashtable to a file. Since that point, getFileListing isn't recognized as a valid symbol.
FileListing2.java:17: error: cannot find symbol
List<File> files = FileListing2.getFileListing(startingDirectory);
symbol: method getFileListing(File)
location: class FileListing2
1 error
Can someone lend a second set of eyes to help me uncover what I accidentally/overwrote. I'm sure it's something obvious. :\
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption.*;
import java.nio.file.Paths;
//
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
}
If your code is all you have for FileListing2, than there is no getFileListing() method for LileListing2, only a main() method
Yeah it IS something very obious, your class FileListing2 does not contain a method getFileListing(File). And it has to be static, the way you're trying to call it:
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
public static List<File> getFileListing(File f) {
/* implementation */
}
}
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