Checking if a string is a compilable Java class - java

I have an application that has stored various classes in string form.
For example, I might have this class:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
that is stored as a string in a database.
I would like to know whether this string contains a class that can compile successfully.
How would I go about doing that? Is there a package for this?

Create a text file and write the code to the file using Java:
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}");
myWriter.close();
Now run the file via
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
You'll get to know if it compiles from its return value.

Related

javac error: Scanner: FileNotFoundException

I'm now writing a java class and want to read a txt file in, like this:
public class Myclass {
...
public static void main(String[] args) {
try{
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
int [] array = new int [1000];
int i = 0;
while(scanner.hasNextInt())array[i++] = scanner.nextInt();}
catch (FileNotFoundException exp) {
exp.printStackTrace();}
}
...
}
And for example, use it like java Myclass input.txt. However when I use javac to compile it in Linux, erros throws:
error: cannot find symbol
catch (FileNotFoundException exp) {
^
symbol: class FileNotFoundException
location: class Myclass
That's weird since name of input file hasn't even been passed in. I've tried File file = new File('input.txt'); and it also throws this error, so I don't know what's wrong (System.out.println(new File('input.txt').getAbsolutePath());will print out the correct and existed path).
You need to add correct imports at the begining of a class:
import java.io.FileNotFoundException;
public class Myclass {...
i think you have to compile your class using the following command
javac com/Trail.java
javac <package-name1>/<package-name2>/<classname.java>
then run the following command
java com.Trail test.txt
the you have to ensure test.txt place then it will works for you, let me recommand you the following answer of the question it helps me a lot to run your code here and here
for where you should put your file
note:
try to declare public static void main(String args[]) throws FileNotFoundException
please you have to be inside folder of file which you want to compile
It looks like you did not import the class FileNotFoundException.
Adding a import java.io.FileNotFoundException at the top of your file should resolve the issue.
Assuming all the imports are alright, the next most likely cause is the txt file is not there. You have to put your txt file at the same folder that there are folders like "src", "dist" and "build".
I've figured it out!
declare main like this:
public static void main(String args[]) throws FileNotFoundException{
...
Try to put the location of file that you want to read, something like this:
File file = new File("C:\\text.txt");
Full example:
public static void main(String[] args)
{
File file = new File("C:\\text.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}

Maintain java object state when calling java process from bash script

public class Go {
private static SomeObject fld;
public static void main(String[] args) {
//depending on the args I do call different methods(among
//them one arg will do the job of initialization of fld variable)
}
}
I call the above java function from the bash script.
while true
do
read commands
java -cp some-jar.jar Go <commands>
then
Say command1 does initialization of fld in the Go class and command2 does some processing over the initialized field.
As I am calling different java processes for the different commands the objects fld state is not getting persisted for the next command.
How can I modify the code such that the fld information gets persisted for the next commands without using some database or deserializing and serializing?
You could store result in bash variable:
Go.java:
class Go {
private static String fld;
public static void main(String[] args) {
fld = args[0];
fld += fld.length();
System.out.println(fld);
}
}
run.sh
VALUE=test
while true
do
VALUE=`java Go $VALUE`
echo $VALUE
done
Output:
test4
test45
test456
test4567
test45678
Or store result into file, read it in bash and pass as parameter into Go.java .
Here is file storage example:
File example Go.java:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
class Go {
private static String fld;
public static void main(String[] args) throws IOException {
fld = args[0];
fld += fld.length();
FileWriter fileWriter = new FileWriter("store.txt");
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(fld);
printWriter.close();
}
}
File example run.sh:
VALUE=store
while true
do
java Go $VALUE
VALUE=`cat ./store.txt`
echo $VALUE
done
File example Output:
store5
store56
store567
store5678

Where does Java save files to?

I ran the below code and created a file. Where can I find it in my filesystem?
import java.io.*;
public class FileReaderDemo {
public static void main(String args[]) throws Exception {
File f = new File ("wayback.txt");
f.createNewFile();
System.out.println(f.exists());
}
}
Add the following to your program, run it and it'll show you the expected location:
System.out.println(f.getCanonicalFile());

How to pipe input from a Java program to another using Bourne Shell

I have two simple Java programs and I want to pipe the result of the "Test" to the "Test2".
public class Test{
public static void main(String args[]){
System.out.println("Hello from Test");
}
}
and
public class Test2{
public static void main(String args[]){
System.out.printf("Program Test piped me \"%s\"",args[0]);
}
}
After I compiled both of .java files I tried to run the pipe command from terminal
java Test | java Test2, but I get an ArrayIndexOutOfBoundsException which means that the args array is not initialized?
How can the Test2 application take the outputstream value that Test.main() produced through piping?
One way is to use xargs:
java Test| xargs -I ARGS java Test2 ARGS
Pipes connect one program’s standard output to another program’s standard input, not to the other program’s command-line arguments.
The second class will not get the piped output as arguments to its main method; it will get the piped output as its standard input. So you want to read the information from System.in:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Test2 {
public static void main(String args[])
throws IOException {
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
stdin.lines().forEachOrdered(
line -> String.format("Program Test piped me \"%s\"", line));
}
}

How do you open the Windows Command prompt using eclipse with java programming?

I am creating a text based program/ game and someone I know created one that opened the console into the Windows Command prompt. This made it so it could be continually refreshed, making the text clear and having a clean look, rather than the clunky console view, which just adds the text onto it, making a bad medium for a text-based game.
The following may give you an idea:
public static void main(String[] args) throws Exception {
// Since you are using eclipse, bin contains the compiled classes
// This depends on your working directory.
File directory = new File("bin");
// In my case, the main class is Game (in the default package)
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "java", "Game");
// directory defined above
pb.directory(directory);
// The fun begins!
pb.start();
}
The Game class containing only the following:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println(sc.nextLine());
}
}
}

Categories

Resources