I created an easy script with notepad++ and run in the cmd with this command:
java -cp . Test
Result:
Error: Main class Test could not be found or loaded
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String fileName = "npcData.csv";
String line = "";
String csvSplitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while ((line = br.readLine()) != null) {
String[] npc = line.split(csvSplitBy);
System.out.println("nonCritSpecialNpc['" + npc[0] + "'] = true;");
}
} catch (IOException e) {
System.out.println("Fehler beim Lesen der Datei: " + e.getMessage());
}
}
}
What am I'm missing?
There are a couple of things you're missing here.
First, for public classes, the name of the class should match the name of the file. I.e., you either need to rename your class to Test, or rename the file to Main.java.
Second, you're missing a crucial step here - compiling. Java is not an interpreted language. You need to convert your .java class to something the JVM can run. This is done using the Java Compiler, or javac for short:
javac Main.java
After doing that, you'll have a .class file that the JVM can execute:
java -cp . Main
Related
I'm trying to run a python script whenever a button on my gui (swing) is pressed. However, the script never runs and I'm not sure how to fix this. I know the script works fine independently, it should be py not python because windows, and my file system ntfs.
So far I've been trying to use code that can be summarized as below:
myBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Process p = Runtime.getRuntime().exec("py myScript.py");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
I don't think I can chmod ntfs stuff but I tried setting permissions via right clicking the python file and trying to mess with the security settings. Full control for the script to users does nothing.
The python script has the following permissions, my guess is my code isn't working because it does not have execute permissions.
-rw-r--r--
Use complete python executable path instead of "py". It executes the file with just read permissions.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
try {
Process p = Runtime.getRuntime().exec("C:/Windows/py myScript.py");
String cmdOutput = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((cmdOutput = stdInput.readLine()) != null) {
System.out.println(cmdOutput);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
myScript.py
print("This line will be printed.")
Output:
C:\Users\Administrator\Documents\demo>javac Sample.java
C:\Users\Administrator\Documents\demo>java Sample
This line will be printed.
I just want some files to be read and written in my Java program. So I use java.security.SecurityManager to manage this, but it seems unsatisfactory.
The Main.java file is below
import java.io.*;
import java.util.*;
public class Main {
static private final String INPUT = "in.txt";
public static void main(String args[]) throws Exception {
FileInputStream instream = null;
BufferedReader reader = new BufferedReader(new FileReader(INPUT));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
}
}
and the file /opt/java.policy like below
grant {
permission java.io.FilePermission "./out.txt", "write";
};
Then I run
java -Xss64m -Xms16m -Xmx512m -Djava.security.manager -Djava.security.policy=/opt/java.policy Main
But there are no errors, the output is what the in.txt is. I tried other file and got the same result. Why does this happen?
From the Javadoc:
Please note: Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.
Not that this is well-specified. Code isn't 'in' a directory: it is executed from a current working directory, and this appears to be what is meant.
I tried to execute a small hive query from Java, but it is failing with below error, bur when I copy the same query and run on terminal it is giving me the result.
Can someone help me on this.
Java Code:
Runtime.getRuntime().exec("hive -e 'show databases;'");
Error thrown:
FAILED: ParseException line 1:5 cannot recognize input near '<EOF>' '<EOF>' '<EOF>' in ddl statement
Regards,
GHK.
I have been working with this Java problem for a while, and I believe I have solved this problem. Basically the reason you are failing is because the environment variables are not ser up properly. put the following in your /home/<username>/.bash_profile file and restart your machine to fix this.
HIVE_HOME=/usr/lib/hive
export HIVE_HOME
PATH=$PATH:$HIVE_HOME/bin/hive
export PATH
This will ensure that they get set up properly.
However while this will get rid of the error it still won't show you a list of databases because the process that runs the hive command will run in the background, not on the console the main program is running from. The following code will let you redirect the outputs of the program to the console that the main program is running from.
package testing.console;
import java.io.IOException;
import java.lang.ProcessBuilder;
import java.util.Map;
import testing.console.OutputRedirector;
//This Works
public class ConsoleTester {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
ProcessBuilder hiveProcessBuilder = new ProcessBuilder("hive", "-e",
"show databases");
String path = processEnv.get("PATH");
Process hiveProcess = hiveProcessBuilder.start();
OutputRedirector outRedirect = new OutputRedirector(
hiveProcess.getInputStream(), "HIVE_OUTPUT");
OutputRedirector outToConsole = new OutputRedirector(
hiveProcess.getErrorStream(), "HIVE_LOG");
outRedirect.start();
outToConsole.start();
}
}
And the OutputRedirector class used to get the output to console.
package testing.console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class OutputRedirector extends Thread {
InputStream is;
String type;
public OutputRedirector(InputStream is, String type){
this.is = is;
this.type = type;
}
#Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(type + "> " + line);
}
} catch (IOException ioE) {
}
}
}
I am running java 7 applications on unix machines. Is there a way to get the current umask value in pure java ?
In C I would use a combination of umask system calls, but I don't think I can call that in Java without resorting to JNI. Is there another approach ?
Edit: Here is a C example (from GUN libc docs):
mode_t
read_umask (void)
{
mode_t mask = umask (0);
umask (mask);
return mask;
}
A simple solution, if there is no Class/Method to get the umask, why don't you get it before call java and pass as a property?
Can you clarify? Do you want to read the umask of the application(the current java process)? Or do you want to read the umask value of some files on the file system?
You can use NIO (the used code is from the javadocs) to get some file attributes, or you can execute a shell command, since the process created with Runtime.execute inherits the umask of it's creator process.
So you should be able to solve your problem without the use of JNI.
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
public class Test {
private static final String COMMAND = "/bin/bash -c umask -S";
public static String getUmask() {
final Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec(COMMAND);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String umask = reader.readLine();
if (process.waitFor() == 0)
return umask;
} catch (final IOException e) {
e.printStackTrace();
} catch (final InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
return "";
}
public static void main(String[] args) throws IOException {
/*
* NIO
*/
PosixFileAttributes attrs = Files.getFileAttributeView(Paths.get("testFile"), PosixFileAttributeView.class)
.readAttributes();
System.out.format("%s %s%n", attrs.owner().getName(), PosixFilePermissions.toString(attrs.permissions()));
/*
* execute shell command to get umask of current process
*/
System.out.println(getUmask());
}
}
I have two projects-try.java and another.java. I would like to run another,java from try.java
here is my code for another.java
package another;
public class Another {
public static void main(String[] args)
{
System.out.println("Another Java Project");
}
}
Here is mycode for try.java
package pkgtry;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Try
{
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null)
{
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception
{
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
public static void main(String[] args)
{
try
{
runProcess("javac C:\\Users\\owner\\Documents\\NetBeansProjects\\try\\src\\pkgtry\\Another.java");
runProcess("java C:\\Users\\owner\\Documents\\NetBeansProjects\\try\\src\\pkgtry\\Another");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
After running the Try.java Its not printing anything. Its just printing build successful in netbeans. But a class Another.cass has been created
Can anyone help me?
The java compiler is trying to find Another.java file inside package pkgtry. If you put both the files in one package then you will able to achieve desired result.
public static void main(String[] args)
{
try
{
runProcess("javac Another.java");
runProcess("java Another");
}
catch (Exception e)
{
e.printStackTrace();
}
}
It looks like Another.java isn't in the directory you're running your code from. In particular, you are managing to invoke both javac and java, and it looks like both are receiving the arguments you've specified - but it can't find Another.java.
Additionally, you need to provide the fully-qualified class name to java, which in this case is another.Another as it's in the another package. That also means you need to compile it in such a way that will leave the class file in an appropriate directory structure.
So you want something like:
runProcess("javac -d . path/to/Another.java");
runProcess("java another.Another");
(Where path/to/Another.java is either an absolute filename or one relative to the working directory.)
The -d . will tell javac to build a directory structure rooted in the current working directory for the output files.
EDIT: Now we know where you're running, you could use:
runProcess("javac -d . src/pkgtry/Another.java");
runProcess("java another.Another");
Note that you should keep your source organized in a folder structure to match the package structure, so it should be in a directory called another, not pkgtry
What about doing like this:
try
{
runProcess("cd C:\\Users\\owner\\Documents\\NetBeansProjects\\try\\src\\pkgtry);
runProcess("javac Another.java");
runProcess("java Another");
}
Is there any chance it could work that way?