I have instruction to run program in command line, for example:
java SetTest < alice30.txt
I wonder how to do this in Eclipse. I tried to put this in Run Configuration like this:
Another thing I don't know is where to put this file (alice30.txt). Is this in root of project or in src folder where source files are located?
I know these are beginner questions but I am stuck and need help.
EDIT:
As #Kane suggested I passed File and opened stream.
Instead of:
Scanner in = new Scanner(System.in);
I now use:
Scanner in = new Scanner(new File("alice30.txt"));
You can pass full file path in arguments (e.g. c:/.../alice30.txt))
The eclipse root directory is the base directory of the project (i.e., not the src/ directory, directly under the project.)
It's generally good style to have a 'resources' folder for txt, graphics, etc.
Rather than trying to pass a stream you could just pass the filename and open the stream yourself.
The reason what you're doing in Eclipse isn't working is because your command prompt/shell/dos/bash/whatever is handling creating the input stream out of the file for you. Eclipse doesn't do this. So, from the command line: < alice.txt means "run this program with no arguments, and create a stream to system.in", while doing that in Eclipse means "run this program with two arguments '<' and 'alice.txt'
you need do like this:
add:
import java.io.IOException;
import java.nio.file.Paths;
then:
replace"Scanner in = new Scanner(System.in);"to"Scanner in =new Scanner(Paths.get("alice30.txt"));" .
and you also need do this : "public static void main(String args[]) throws IOException "
With information from this link/page and several tries, I figure out a way to pass argument and file using the local route in eclipse Run -> Run Configurations.. , though it is not recommended as Kane said.
For my case: I need to do " $java someClass tinyW.txt < tinyT.txt " (This is an example from Algorithms book by Robert Sedgewick)
In my case, " tinyW.txt " is a argument, so in the eclipse environment, you can set in Run -> Run Configurations -> Arguments -> Program arguments: /local address/tinyW.txt. For my Ubuntu: /home/****/tinyW.txt
" < tinyT.txt " is a file that pipe to the main arguments, so you can set the route and file in " Run -> RUn Configurations -> Common ", click the "Input File", use the File System icon and select the file from local compute. See the figure. So in Input File: /local_address/tinyT.txt. My case is: /home/***/tinyT.txt. Hope it also works for you.
Related
I'm on latest Windows 10. I have JDK 15. Latest Visual Studio Code (System). In VS Code, I have half of the Java Extension Pack Installed, i.e Language Support for Java (Red Hat) | Debugger for Java (Microsoft) | Visual Studio IntelliCode (Microsoft). So I did that to just get that run button on the top right (the default installed VS Code didn't have that run button for JAVA programs), below the close button, to that I can run the JAVA programs inside the VS Code. I didn't wanna go out to the directory then open Power Shell or CMD and then write java filename.java and run the program...
Now the issue is that when I click the run button, I think, a Power Shell is opened inside the VS Code and then something other than "java FileName.java" is being written. Because of that I can't really see what the compilation error is. I can only see the line number where the problem is, not actually the solution for that. || If I run the same in the PowerShell outside the VS Code with this "java FileName.java", I can see that there is some issue at x line and also the solution for the same.
So I wanted to know if there is any way to get this type of output inside the Visual Studio Code.
Or if there is any way that Instead of writing a lot of thing like this, we can simple tell the Visual Studio Code to run "java fileName.java" inside VS Code when I click the Run Button at the top.
EDIT:
The Code that I'm running is this one.....
File Name - test.java
import java.io.*;
public class SOPFileTest{
public static void main(String arr[]){
try{
// Creating a File object that represents the disk file.
PrintStream o = new PrintStream(new File("A.txt"));
// Store current System.out before assigning a new value
PrintStream console = System.out;
// Assign o to output stream
System.setOut(o);
System.out.println("Test 1");
// Use stored value for output stream
System.setOut(console);
System.out.println("Test 2");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Now I've noticed somethings, they are:
-When (FileName == Class Name)
---Then (VS Code)
-----Prints the Last System.out.println in the console
-----A.txt is not created / written inside
---Then (Powershell)
-----Prints the Last System.out.println in the console
-----A.txt is created and/or written inside
-When (FileName != Class Name)
---Then (VS Code)
-----shows the error same as the image that I included above.
---Then (Powershell)
-----Prints the Last System.out.println in the console
-----A.txt is created and/or written inside
So powershell works as I intend it would, the VS Code isn't...
If the filename is different from ClassName, java extension will detect it and throws probelms, which is build failed and you can choose if continue:
If you choose proceed, there should be:
[UPDATE -- Screenshot in Powershell:]
It's about the same as problems shown in VS Code.
Java extension requires class must be defined in its own file, so filename should be as the same as ClassName, then everything works well, no matter in integrated Terminal in VS Code, or in the PowerShell outside VS Code:
So I wanted to know if there is any way to get this type of output
inside the Visual Studio Code.
Keeping the filename and classname same makes sure it could be built and compiled successfully, which is the first step.
And the text file should be generated in current working directory, check it in your file explorer.
I want to open a file in .jar application and I want to use java to do this. Explaining, for example I have the file SF_Antivalent.xml and I want to open it with uppaal.jar. How do I do this using Java. I've written the following code, but it doesn't work.
public class test7 {
public static void main(String[] args){
Runtime rt=Runtime.getRuntime();
String file="C:\\Users\\V\\Documents\\diplwmatiki\\SFBs\\SF_Antivalent.xml";
Process p=rt("C:\\Windows\\System32\\java.exe", "-jar", "C:\\Users\\"
+ "V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar" + file);
}
}
and I get this error: the method rt(String, String, String) is undefined for the type test.
Is there something to do?
You question is a little confusing, however, I believe you want to run some application and pass the XML file as a parameter to it...
The problem is, you're treating rt as a function/method, not an object. Runtime has the an exec method used to execute external commands, for example...
Runtime rt=Runtime.getRuntime();
String file="C:\\Users\\V\\Documents\\diplwmatiki\\SFBs\\SF_Antivalent.xml";
Process p=rt.exec(new String[]{
"C:\\Windows\\System32\\java.exe",
"-jar",
"C:\\Users\\V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar",
file});
Also, each command or argument you want to send to this external process must be it's own element within the array you pass to this method
This means tha "V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar" + file won't actually have the effect you think it will.
I'd also recommend that you use ProcessBuilder over Runtime#exec, but that's me.
The reason you are getting the error is because rt is a Runtime object, not a method. To call a method of rt do this:
rt.someMethodName();
With the code above you cannot get XML file, you're trying to execute something, instead of opening file inside JAR archive
Look into getResourceAsStream, this will give you possibility to load any file from JAR
I've been looking to incorporate a Python Script a friend made for me into a Java application that I am trying to develop. After some trial and error I finally found out about 'Jython' and used the PythonInterpreter to try and run the script.
However, upon trying to run it, I am getting an error within the Python Script. This is odd because when I try run the script outside of Java (Eclipse IDE in this case), the script works fine and does exactly what I need it to (extract all the images from the .docx files stored in its same directory).
Can someone help me out here?
Java:
import org.python.core.PyException;
import org.python.util.PythonInterpreter;
public class SPImageExtractor
{
public static void main(String[] args) throws PyException
{
try
{
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py");
}
catch(Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
}
Java Error regarding Python Script:
Traceback (most recent call last):
File "C:/Documents and
Settings/user/workspace/Intern
Project/Proposals/Converted
Proposals/Image-Extractor2.py", line
19, in
thisDir,_ = path.split(path.abspath(argv[0]))
IndexError: index out of range: 0
Traceback (most recent call last):
File "C:/Documents and
Settings/user/workspace/Intern
Project/Proposals/Converted
Proposals/Image-Extractor2.py", line
19, in
thisDir,_ = path.split(path.abspath(argv[0]))
IndexError: index out of range: 0
Python:
from os import path, chdir, listdir, mkdir, gcwd
from sys import argv
from zipfile import ZipFile
from time import sleep
#A few notes -
#(1) when I do something like " _,variable = something ", that is because
#the function returns two variables, and I only need one. I don't know if it is a
#common convention to use the '_' symbol as the name for the unused variable, but
#I saw it in some guy's code in the past, and I started using it.
#(2) I use "path.join" because on unix operating systems and windows operating systems
#they use different conventions for paths like '\' vs '/'. path.join works on all operating
#systems for making paths.
#Defines what extensions to look for within the file (you can add more to this)
IMAGE_FILE_EXTENSIONS = ('.bmp', '.gif', '.jpg', '.jpeg', '.png', '.tif', '.tiff')
#Changes to the directory in which this script is contained
thisDir = getcwd()
chdir(thisDir)
#Lists all the files/folders in the directory
fileList = listdir('.')
for file in fileList:
#Checks if the item is a file (opposed to being a folder)
if path.isfile(file):
#Fetches the files extension and checks if it is .docx
_,fileExt = path.splitext(file)
if fileExt == '.docx':
#Creates directory for the images
newDirectory = path.join(thisDir, file + "-Images")
if not path.exists(newDirectory):
mkdir(newDirectory)
currentFile = open(file,"r")
for line in currentFile:
print line
sleep(5)
#Opens the file as if it is a zipfile
#Then lists the contents
try:
zipFileHandle = ZipFile(file)
nameList = zipFileHandle.namelist()
for archivedFile in nameList:
#Checks if the file extension is in the list defined above
#And if it is, it extracts the file
_,archiveExt = path.splitext(archivedFile)
if archiveExt in IMAGE_FILE_EXTENSIONS:
zipFileHandle.extract(archivedFile, newDirectory)
except:
pass
My guess is that you don't get command line arguments if the interpreter is called (well not that surprisingly, where should it get the correct values? [or what would be the correct value?]).
os.getcwd()
Return a string representing the current working directory.
Would return the working dir, but presumably that's not what you want.
Not tested, but I think os.path.dirname(os.path.realpath( __ file__)) should work presumably (Note: remove the space there; I should look at the formatting options in detail some time~)
I have an error in my first step with Java, so when i try to run the code hello world:
class apples{
public static void main(String args[]){
System.out.println("Hello World!");
}
}
I go to: - Run as .. -> Then i choose Java aplicacion - > And i press Ok
But when i press Ok does not appear the window down to show me the correct message Hello World
Your code works fine for me:
class apples
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
I downloaded it to c:\temp\apples.java.
Here's how I compiled and ran it:
C:\temp>javac -cp . apples.java
C:\temp>dir apples
Volume in drive C is HP_PAVILION
Volume Serial Number is 0200-EE0C
Directory of C:\temp
C:\temp>dir ap*
Volume in drive C is HP_PAVILION
Volume Serial Number is 0200-EE0C
Directory of C:\temp
08/15/2010 09:15 PM 418 apples.class
08/15/2010 09:15 PM 123 apples.java
2 File(s) 541 bytes
0 Dir(s) 107,868,696,576 bytes free
C:\temp>java -cp . apples
Hello World!
C:\temp>
Your lack of understanding and the IDE appear to be impeding your progress. Do simple things without the IDE for a while until you get the hang of it. A command shell and a text editor will be sufficient.
Sorry about missing javac; cut & paste error.
If you look at the screenshot, your class name is there, last in the list. Select it and press OK. To not see this message again, right-click on the class name on the left side and select there Run...->Java Application.
The only problem that causes your error here is that the classname and the filename do not match - and they have to.
Solution
Rename either the file thesame.java to apple.java or the class to thesame. Then if you select "Run as..." again, eclipse will present a menu item to start your Java application.
(other mentioned, that there's no requirement that a top-level class and the filename do match - unless the top level class is public. Of course this is true. But the problem was about "running" a class under eclipse as a Java application)
Try public class apples and make sure the file is apples.java. Also it should be public static void main(String[] args)
You have 2 classes by name of "thesame.java" under the source folder. Since one is directly under the src folder, and other under (default package), they use the same namespace, hence Interpreter is confused which java file to execute and is asking you to select the class you want to execute.
Class names must be capitalized... so change apples to Apples. Also, if you are a beginner (which it seems like), I would recommend the Netbeans IDE -- it's a bit more friendlier for new users than Eclipse.
You class must be named "thesame" if you store it in a file called "thesame.java", as you have. Either rename your class to "thesame" or change the file to be "apples.java".
You should move the "[]" to be before "args". So, String[] args.
Either select "apples" at the bottom of the menu you posted and run it, or right-click on the Java file and make it the default thing to run for this project. Or launch it by right-clicking on the file and selecting "run".
I have a bat file with the following contents:
set logfile= D:\log.txt
java com.stuff.MyClass %1 %2 %3 >> %logfile%
when I run the bat file though, I get the following:
C:\>set logfile= D:\log.txt
C:\>java com.stuff.MyClass <val of %1> <val of %2> <val of %3> 1>>D:\log.txt
The parameter is incorrect.
I'm almost positive the "The parameter is incorrect." is due to the extraneous 1 in there. I also think this might have something with the encoding of the .bat file, but I can't quite figure out what is causing it. Anyone ever run into this before or know what might be causing it and how to fix it?
Edit
And the lesson, as always, is check if its plugged in first before you go asking for help. The bat file, in version control, uses D:\log.txt because it is intended to be run from the server which contains a D drive. When testing my changes and running locally, on my computer which doesn't have a D drive, I failed to make the change to use C:\log.txt which is what caused the error. Sorry for wasting you time, thanks for the help, try to resist the urge to downvote me too much.
I doubt that that's the problem - I expect the command processor to deal with that part for you.
Here's evidence of it working for me:
Test.java:
public class Test
{
public static void main(String args[]) throws Exception
{
System.out.println(args.length);
for (String arg : args)
{
System.out.println(arg);
}
}
}
test.bat:
set logfile= c:\users\jon\test\test.log
java Test %1 %2 %3 >> %logfile%
On the command line:
c:\Users\Jon\Test> [User input] test.bat first second third
c:\Users\Jon\Test>set logfile= c:\users\jon\test\test.log
c:\Users\Jon\Test>java Test first second third 1>>c:\users\jon\test\test.log
c:\Users\Jon\Test> [User input] type test.log
3
first
second
third
the 1 is not extraneous: it is inserted by cmd.exe meaning stdout (instead of ">>", you can also write "1>>". contrast this to redirecting stderr: "2>>"). so the problem must be with your parameters.
This may seem like a stupid question, but is there an existing D: drive in the context that the bat file runs in?
Once I had a case where a bat file was used as the command line of a task within the Task Manager, but the Run As user was set to a local user on the box, giving no access to network drives.
Interpolated for your case, if the D: drive were a network drive, running the bat file as, say, the local administrator account on that machine instead of a domain user account would likely fail to have access to D:.