I have written the following code in Java:
public class test {
public static void main(String[] args) throws IOException {
FileWriter f = new FileWriter(new File("C:\\Users\\john\\Desktop\\x.txt"));
f.write("hello world!");
f.close();
}
}
It works correctly (creates a file called x.txt on the desktop containing "hello world!")
And I have this VBA script
Sub Macro1()
'
' Macro1 Macro
'
'
Dim objShell As Object
Dim JavaExe, JavaScript As String
Set objShell = VBA.CreateObject("Wscript.Shell")
JavaExe = """C:\Users\john\eclipse-workspace\eclipseCode\src\test.java"""
JavaScript = "C:\Users\john\Desktop\x.txt"
objShell.Run JavaExe & JavaScript
End Sub
But it does not execute the java code. It simply opens the file from java eclipse as a .txt file.
Is it possible to run java eclipse from Excel VBA? Any help is greatly appreciated, thanks.
What you want to implement in your "objShell.Run" is actually RUNNING Java from the command line with your program as an argument.
What you are ACTUALLY doing is pointing to the Java file and saying "Do this file" and the system is saying "OK. I know what to do with this. I open .java files in a text editor!".
Research how to compile & run java programs using javac/java.
To test this process, first ignore Eclipse and VBA and just go to a normal command prompt (cmd) and figure out the co mmands to compile & run the java to see what command line you need.
Hint: You will need to compile with javac & then run with java. Something like "javac test.java" and "java test" in the directory your file is in.
Should be straightforward from there.
Related
I am running OSX 10.11 with IntelliJ 14.1.15.
I have a programme which takes a txt file as an argument. I can run it from the terminal through java SearchCmd test.txt and then it allows me to enter a search term and searches that list.
How do I do this from within IntelliJ, so that I can click the run button and it reads the file and I am able to enter a search term in the IntelliJ console.
The main class 'SearchCmd' contains the main method, as such:
public class SearchCmd {
public static void main (String[] args) throws IOException {
String name;
// Check that a filename has been given as argument
if (args.length != 1) {
System.out.println ("Usage: java SearchCmd <datafile>");
System.exit (1);
}
// Read the file and create the linked list
HTMLlist l = Searcher.readHtmlList (args[0]);
}
However, when I try and run this it says: "Usage: java SearchCmd ".
In order to pass the test.txt file to IntelliJ, I entered the file path in the 'Run/Debug Configurations'.
Sadly I can't attach the picture. :-(
Any help on fixing this and helping me run it from IntelliJ will be greatly appreciated.
Go to Run -> Edit Configurations, Select Application, then give the main class name and program arguments. Then Run.
I just figured it out.
So instead of pasting in an absolute path, you need to paste a relative path from the root directory of your IntelliJ project. And most importantly you have to ommit the initial forward slash.
So my absolute path to the file might be this:
Computer/project/TestInput/itcwww-small.txt
But the path that I need to put into Programme Arguments is:
TestInput/itcwww-small.txt
I hope that this will help someone else.
I had the same issue and was very confused with the previous answers of this question, so here is my explanation to anyone that is lost like I was.
With the project open.
Run > Edit Configurations....
Add the whole directory that the file is in it on the Program
Arguments field with the file format at the end.
Steps to follow-
1. Run->Edit Configurations.
2. Select Application.
3. Provide main class name and command line arguments and apply.
4. Run
Adding the input file name's relative path in the "Program Arguments" will allow the "main" method reading the argument in as a "String"
However, in order to actually let the System to understand using data from the file as standard input, it seems we have to specifically read the file and set the input stream as the system input :
try {
FileInputStream inputStream = new FileInputStream(new File(args[0]));
System.setIn(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You need to go in the menu Run -> Edit configurations.
Select your configuration and add the parameters in the field Program arguments
The field Program arguments is what appears after the class name from command line. For example:
java MyMainClass ProgramArgument1 ProgramArgument2 ProgramArgument3
in your example
java SearchCmd test.txt
the program argument is test.txt
Note: Use an absolute path or check that the working directory is the directory containing your file
I have the below code
public class prob01 {
public static void main (String arg[]) {
System.out.println(arg[0]);
}
}
I have a text file prob01.txt in the same directory which contains: StackOverflow StackExchange
How can I get the output as StackOverflow from the above code when I give the arguments as prob01.txt like below: (I dont want to modify the java code, the dos has to take care of parsing the file and sending the contents as arguments)
C:\> javac prob01.java
C:\> java -cp . prob01 < prob01.txt
You'll need to use Reader in java code to read the content of the file.
I know that you must add command line arguments into the "Run Configurations" in Eclipse to get your command line arguments to be passed every time by default. This worked fine on my PC.
The purpose of this question is to create a simple program that can be submitted to an online programming challenge site (like codeeval). The system provides a file path to the command line args[0] and then you manipulate the file and its data.
On the PC I had my Class folder > Default Package > (file.txt and TestCode.java)
The project was set up with a run configuration with simply file.txt in the program arguments section.
On the MAC this doesn't seem to be working. I get a fileNotFoundExcepion. I'm new to MAC so I'm thinking this might be a problem with file extensions not being what I think they are. I saved a file as "file.txt" but if I save it as "file" MAC doesn't show the file extensions and I'm not sure if MAC supports .txt by default.
If it doesn't support .txt, what file type is a "text document"? I tried saving the text document as "file" leaving off any extension, and then adding file.rtf or file.txt or even file to the Program arguments and none of that works. It all gives me a fileNotFoundException.
EDIT
The intent is to be able to develop solutions to the CodeEval (or similar) website and submit them. I have previously solved many problems on CodeEval and turned them in with the code below from a PC. This, however, doesn't work on MAC. The answer involving the use of the URL does not work when run from the solution checking platform (presumably because the program is not actually saved onto the system).
EDIT 2
My entire program:
public class TestCode {
public static void main (String[] args)throws IOException{
File filename = new File(args[0]);
Scanner file = new Scanner(filename); // returns the fileNotFoundException
while( file.hasNextLine()){
String line = file.nextLine();
System.out.println(line);
}
}
}
Under "Run Configurations" in the Arguments tab > Program Arguments I have tried putting file, file.txt, file.rtf all three with a "text document" in the same directory as the above program. I have tried naming that file file, file.txt and file.rtf And i tried every combination of these names.
Did you try to use the absolute file name as command line parameter? This should be something like /Users/name/path/to/your/file. If the file is part of your project, you can also use a variable such as ${project_loc}/file (try the button Variables… below the Program Arguments field.
Replace your code with this
URL resource = TestCode.class.getResource(args[0]);
Scanner file = new Scanner(new File(resource.getFile()).getAbsoluteFile());
I'm trying to connect a Java project with a website. The project is located in "website_folder/data/backend" and at that time, I want to test if the following example works:
[java code]
public static void main(string args[]) {
if(args[0].equals("5") {
File f = new File("/location/to/file/result.txt");
if(!f.exists()) {
f.createNewFile();
FileWriter fstream = new FileWriter("/location/to/file/result.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("It works!");
out.close();
}
}
}
And in the PHP file I have to following command:
<?php
exec("java -cp /data/backend/Project/build/classes/project/Main.class/ main 5",$output);
?>
but nothing happens! I mean, the file isn't created in the directory I have specified in the main method. I have tried to run the .jar file of the project in the PHP command, to pass the argument "5" via a variable, to add to the directory path -in the exec command- this: "i:/xampp/htdocs/website_folder/" (I:\ is the disk drive where I have my virtual server -xampp- installed), but in vain. Am I doing something wrong with the syntax of the command?
Edit:
I changed the command to point the .jar file (java -jar /data/backend/Project/dist/Project.jar 5) and the problem is solved.
Try this:
"java -cp /data/backend/Project/build/classes/ project.Main 5"
This assumes, that the class which contains your main method is in package project and is called Main. If this is not the case, adapt accordingly.
I am trying to Compress and Archive all the files in a folder, using Java Runtime class. My code snippet looks as this :
public static void compressFileRuntime() throws IOException, InterruptedException {
String date = Util.getDateAsString("yyyy-MM-dd");
Runtime rt = Runtime.getRuntime();
String archivedFile = "myuserData"+date+".tar.bz2";
String command = "tar --remove-files -cjvf "+archivedFile+" marketData*";
File f = new File("/home/amit/Documents/");
Process pr = rt.exec(command, null, f);
System.out.println("Exit value: "+pr.exitValue());
}
The above code doesn't archive and compress the file as expected, though it creates a file myuserData2009-11-18.tar.bz2 in the folder "/home/amit/Documents/".
Also the output is
Exit value: 2.
While if I execute the same command from command line, it gives the expected result.
Please tell me what I am missing.
Thanks
Amit
The problem lies in this part:
" marketData*"
you expect the filenames to be compressed to be globbed from the * wildcard. Globbing is done by the shell, not by the tools themselves. your choices are to either:
numerate the files to be archived yourself
start the shell to perform the command ("/bin/sh -c")
start tar on the folder containing the files to be archived
Edit:
For the shell option, your command would look like:
String command = "sh -c \"tar --remove-files -cjvf "+archivedFile+" marketData*\"";
(mind the \"s that delimit the command to be executed by the shell, don't use single quotes ot the shell won't interpret the glob.)
If really you want to create a bzip2 archive, I'd use a Java implementation instead of a native command which is good for portability, for example the one available at http://www.kohsuke.org/bzip2/ (it is not really optimized though, compression seems to be slower than with Java LZMA).