Is there any possible way to retrieve information of my graphic card adapter using Java API?
I know that DirectX can easily do it, however, I just wonder if Java can do this...?
Like picture below.. DirectX finds out GPU adapter integrated to my hardware, and a list of its supporting resolutions.
My problem is, is there an API that Java would do this kind of thing?
I really wonder if Java is able to get information regarding to Video Card.
Thank you.
As #Sergey K. said in his answer there are several ways to do this. One of these is using dxdiag tool (obviously it will only work on Windows) particularly dxdiag /t variant that will redirect the output to a given file. Then you can process that file to get required info:
public static void main(String[] args) {
try {
String filePath = "./foo.txt";
// Use "dxdiag /t" variant to redirect output to a given file
ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","dxdiag","/t",filePath);
System.out.println("-- Executing dxdiag command --");
Process p = pb.start();
p.waitFor();
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
System.out.println(String.format("-- Printing %1$1s info --",filePath));
while((line = br.readLine()) != null){
if(line.trim().startsWith("Card name:") || line.trim().startsWith("Current Mode:")){
System.out.println(line.trim());
}
}
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
}
Generated file will look like this:
And output will look like this:
-- Executing dxdiag command --
-- Printing ./foo.txt info --
Card name: Intel(R) HD Graphics Family
Current Mode: 1366 x 768 (32 bit) (60Hz)
There are several ways you can do this in Java. But all of them end up using DirectX/OpenGL/C++/WinAPI/whatever as their back-end.
You will need Java bindings for either of this API. Or you can write your code in C/C++ and use it via JNI.
Related
I am pretty new to both Java and Python, although I have some experience in programming. For an assignement, I need to create a program which uses Java in some way. My project would use Java as an UX, and Python for signal processing and feature extraction, since it has some good tools for that.
However, my question is how to establish communication between both programse. Maybe this question has been asked before, but since I do not know the best terms, I could not find answers.
In my Java Program, I can get the file path to a .csv file, send it to Python, and Python returns the original signals and processed signals. For that, I wrote:
private static void sendPython(String path, JTextField console)
{
String pathPython = "C:\\Users\\gonca\\Desktop\\untitled0.py";
String [] cmd = new String[3];
cmd[0] = "python";
cmd[1] = pathPython;
cmd[2] = path;
Runtime r = Runtime.getRuntime();
try
{
Process p = r.exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = "";
while((s = in.readLine()) != null)
{
console.setText(s);
}
}
catch (IOException e)
{
console.setText("Unable to run python script");
}
}
I was thinking of having the py script output the signals in separated lines, with values separated by "," or ";", and using the BufferedRead to read each line, separate the values and create a new ArrayList from the separated values.
However, before starting working harder to do that, I would like to know if that is the best way to proceed, or is there a more efficient way to do it.
There are more ways to do that:
Solution 1:
Use the python library from java with System.loadLibrary, and call the python method. (here is an example using C/C++: Calling a python method from C/C++, and extracting its return value)
Solution 2:
Launch python as another process, and use D-Bus (or something similar) to communicate with it.
Since you have not mentioned how robust your application is I can think of a solution which can be used if you are planning for a higher level architecture.
Create a python based web application (HTTP server) with all logic to process your files.
Create a java app which can communicate via HTTP python server to get the CSV processed information.
Try to avoid Runtime execution of commands with in your codes that faces user as if it not is properly managed there is always a chance for security breach
Recently I am trying to write an java application to call SCM.exe to execute the code loading job. However, after I successfully execute the SCM load command via java, I found that I actually cannot really download the code (as using the command line, the password need to be entered after execute the SCM load command). May I know how can I enter this password just after I use the process to run the SCM in java? How can I get the output of the command line and enter something into the command line?
Thanks a million,
Eric
Since I don't know what exactly SCM.exe in your case is, I'm answering only what deals with the input/output redirection requirements in an abstract sense. I assume further that you are calling SCM.exe with whatever parameters it needs through System("...") and this is where you are unable pass any further input (stdin of the called process).
You need, instead, to be able to, upon receiving the request for password, pass it to the stdin of the other process, which is solved by using pipes in the classical sense (since you are presumably on Windows, YMMV). More generally, you are dealing with a very simple case of IPC.
In Java you may find an adequate solution by using ProcessBuilder [1] (never did myself, though -- i'd use things a lot simpler than java for this purpose, but I digress...).
An outline of a solution would be:
call the process, having its input and output being handled as output/input streams from your caller java process.
read the output of your process until you are queried the password
write the password
carry on as needed.
If you need further clarification you may need to give more details about your scenario.
[1] http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
public class test {
public static void main(String[] args){
try {
System.out.println("");
String commands = "C:/swdtools/IBM/RAD8/scmtools/eclipse/scm.exe load -d C:/users/43793207/test -i test -r eric-repo";
// load -d C:/users/43793207/test -i test -r eric-repo
test test=new test();
test.execCommand(commands);
} catch (Exception e) {
e.printStackTrace();
}
}
public void execCommand(String commands){
//ProcessBuilder pb = new ProcessBuilder(Command);
//pb.start();
String line;
try {
//Process pp = Runtime.getRuntime().exec(commands);
System.out.println(commands);
Process process = new ProcessBuilder(commands).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
I'm trying to convert files from png's to pdf using imagemagick and Java. I've got everything working to a place when I'm executing imagemagick command to actually merge multiple png's into one pdf. The command itself looks properly, and it works fine when executed in the terminal but my application gives me error showing that imgck can't open the file (even though it exists and I've set permissions to the folder to 777 :
line: convert: unable to open image `"/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001005.png"': No such file or directory # error/blob.c/OpenBlob/2642.
This is my command :
/opt/local/bin/convert "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001005.png" "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001219.png" "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/complete-exportedPanel2013-01-1003:13:17.212.pdf"
And my Java code :
String filesString = "";
for (String s : pdfs){
filesString += "\""+ s + "\" ";
}
Process imgkProcess = null;
BufferedReader br = null;
File f1 = new File(pdfs[0]);
//returns true
System.out.println("OE: "+f1.exists());
String cmd = imgkPath+"convert "+ filesString+ " \""+outputPath+outName+"\"";
try {
imgkProcess = Runtime.getRuntime().exec(cmd);
InputStream stderr = imgkProcess.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
br = new BufferedReader(isr);
} catch (IOException e1) {
msg = e1.getMessage();
}
imgkProcess.waitFor();
while( (line=br.readLine() ) != null){
System.out.println("line: "+line);
}
The whole code is executed from a java servlet controller after getting request from a form. Any ideas what can cause this ? I'm using latest imgck, jdk, and osx 10.7 .
A few things:
When spawning anything but really trivial processes, it's usually better to use ProcessBuilder than Runtime.exec() - it gives you much better control
Even with ProcessBuilder, it often works better to write a shell script that does what you need. Then spawn a process to run the script. You get a lot more control in shell script than you do in ProcessBuilder
Remember that a spawned process is not a shell. It can't, for instance, evaluate expressions, or expand shell variables. If you need that, then you must execute a shell (like sh or bash). Better yet, write a shell script as described above
If all you need to do is to execute some ImageMagick commands, it would probably be easier to jmagick, a Java interface to ImageMagick - see http://www.jmagick.org/
Actually, since the you're assembling images into a PDF, the iText library - http://itextpdf.com is probably the best tool for the job, as it is native Java code, does not require spawning a native process, and will therefore be much more portable.
Solved it by adding all arguments to an arrayList and then casting it to String array.
ArrayList<String> cmd = new ArrayList<String>();
cmd.add(imgkPath+"convert");
for (int i=0, l=pdfs.length; i<l; i++){
cmd.add(pdfs[i]);
}
cmd.add(outputPath+outName);
imgkProcess = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
I wrote a program that creates a set of data that is outputted to an excel spreadsheet. I was originally using the jexcel library to write the data to the file, but I'd like to update the program so that it can check and see whether is should create a ".xls" or ".xlsx" file, then write to the appropriate document type. Apache POI seems to be the best option in terms of writing to a ".xlsx" file, but any ideas about determining the correct file type?
I could just have the user choose when naming the file, but that seems like extra work for the user and I'm assuming that there are users who don't know what file type they'd want.
Any ideas?
Also, I'm assuming the OS is windows and the user has some version of excel, in other cases I'll just choose a default file type.
One way is to call the Windows ASSOC and FTYPE commands, capture the output and parse it to determine the Office version installed.
C:\Users\me>assoc .xls
.xls=Excel.Sheet.8
C:\Users\me>ftype Excel.sheet.8
Excel.sheet.8="C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE" /e
Here a quick example :
import java.io.*;
public class ShowOfficeInstalled {
public static void main(String argv[]) {
try {
Process p = Runtime.getRuntime().exec
(new String [] { "cmd.exe", "/c", "assoc", ".xls"});
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String extensionType = input.readLine();
input.close();
// extract type
if (extensionType == null) {
System.out.println("no office installed ?");
System.exit(1);
}
String fileType[] = extensionType.split("=");
p = Runtime.getRuntime().exec
(new String [] { "cmd.exe", "/c", "ftype", fileType[1]});
input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String fileAssociation = input.readLine();
// extract path
String officePath = fileAssociation.split("=")[1];
System.out.println(officePath);
}
catch (Exception err) {
err.printStackTrace();
}
}
}
You may want to add more error checking and the parsing to extract the Office version from the returned path is left as an exercise ;-)
You can search in the registry for the key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths
This will probably require some work, as evidenced by this question:
read/write to Windows Registry using Java
If you're willing to dive into the registry (eg with jregistrykey) a translated version of this PowerShell script should do what you want.
Take a look at OfficeVer.
You can implement it to your script or use it for code analysis. It's cross-platform much like Java, so compiling it and implementing it directly shouldn't be a big deal.
It works by extracting .docx and xlsx files and then reading the version, as well as reading directly from .doc and .xls files.
OfficeVer as well has extended their support to .pdf files (current version as of time of writing is 1.03.1)
I have a python application which I cant edit its a black box from my point of view. The python application knows how to process text and return processed text.
I have another application written in Java which knows how to collect non processed texts.
Current state, the python app works in batch mode every x minutes.
I want to make the python
processing part of the process: Java app collects text and request the python app to process and return processed text as part of a flow.
What do you think is the simplest solution for this?
Thanks,
Rod
I don't know nothing about Jython and the like. I guess it's the best solution if you can execute two programs without executing a new process each time the Java app needs to transform text. Anyway a simple proof of concept is to execute a separate process from the Java App to make it work. Next you can enhance the execution with all that tools.
Executing a separate process from Java
String[] envprops = new String[] {"PROP1=VAL1", "PROP2=VAL2" };
Process pythonProc = Runtime.getRuntime().exec(
"the command to execute the python app",
envprops,
new File("/workingdirectory"));
// get an outputstream to write into the standard input of python
OutputStream toPython = pythonProc.getOutputStream();
// get an inputstream to read from the standard output of python
InputStream fromPython = pythonProc.getInputStream();
// send something
toPython.write(.....);
// receive something
fromPython.read(....);
Important: chars are NOT bytes
A lot of people understimate this.
Be careful with char to byte conversions (remember Writers/Readers are for chars, Input/OutputStreams are for bytes, encoding is necesary for convertir one to another, you can use OuputStreamWriter to convert string to bytes and send, InputStreamReader to convert bytes to chars and read them).
Look into Jython - you can run Python programs directly from Java code, and interact seamlessly back and forth.
Use ProcessBuilder to execute your Python code as a filter:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PBTest {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("python", "-c", "print 42");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
String s;
BufferedReader stdout = new BufferedReader (
new InputStreamReader(p.getInputStream()));
while ((s = stdout.readLine()) != null) {
System.out.println(s);
}
System.out.println("Exit value: " + p.waitFor());
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Expose one of the two as a service of some kind, web service maybe. Another option is to port the python code to Jython
One possible solution is jpype. This allows you to launch a JVM from Python and pass data back and forth between them.
Another solution may be to write the Python program as a filter (reading data from stdin and writing result to stdout) then run it as a pipe. However I do not know how well Java supports this - according to the Sun docs their concept of pipes only supports communication between threads on the same JVM.
An option is making the python application work as a server, listens for request via sockets (TCP).