It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have this in the File.java:
public static void main(String args[]) throws Exception_Exception {
URL wsdlURL = CallSService.WSDL_LOCATION;
if (args.length > 0) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
and I want to transfer this to a JSP file, so I do like that:
List<String> Search(String keyS){
if(keyS!=null){
QName SERVICE_NAME = new QName("http://ts.search.com/", "callSService");
String arg=??????????????;
URL wsdlURL = CallSService.WSDL_LOCATION;
File wsdlFile = new File(arg);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(arg);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
I want to replace the args[0] with arg. What does (String args[]) mean? and how can I replace it ?
String args[] is an array of Strings passed in from the command line.
So, if you started your app with java MyApp arg1 arg2
Then args[] would contain => ["arg1", "arg2"]
Java will automatically split up arguments separated by spaces, which is how it knows how many arguments you passed in.
Don't do this in a JSP :(
Don't put your functionality in a main, it's confusing: public static void main is conventionally a program's entry point, not a general purpose method. You may use it as one, but IMO it is misleading.
Instead, create an instance method you can call with the argument you want. It could be a static method, but this builds in some inflexibility making things more difficult to test. Embeddeding the code in a JSP also increases testing difficulty.
You'll need to use ServletContext.getRealPath() to get a file relative to the web app, unless you're providing an absolute path. If the file is "embedded" in the app (on the classpath) you'll want to use one of the resourceAsStream variants.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I setup my main to accept command switches?
a source port (-s source_port) and the destination hostname (-h hostname) and port (-p port) of the receiving application as well as the audit log file (-l log_file). One IDS misuse keyword (–m misuse_keyword) and a misuse threshold (-t misuse_threshold) are also specified on the command line.
Basically, I want to have -h localhost set a field named hostname = localhost and -l bob.txt set to a field named inputfile = "bob.txt". How do I do this in Java? I can do this in C and C++ but not sure how to do this in Java.
public static void main(String[] args) {
}
In java if you pass -h hostname -p port you will receive array with 4 elements {"-h", "hostname", "-p", "port"}. So you will have to manage the keys parsing manually.
Here is an example:
private static final String HOST_KEY = "-h";
private static final String PORT_KEY = "-p";
public static void main(String[] args)
{
String host = "";
String port = "";
for(int i=0; i<args.length; i+=2)
{
String key = args[i];
String value = args[i+1];
switch (key)
{
case HOST_KEY : host = value; break;
case PORT_KEY : port = value; break;
}
}
}
Do something like this in your main() method
args = new String[12];
args[0]="-s";
args[1]="source_port";// something integer value "1324"
args[2]="-h";
args[3]="hostname";
args[4]="-p";
args[5]="port";
args[6]="-l";
args[7]="log_file";
args[8]="-m";
args[9]="misuse_keyword";
args[10]="-t";
args[11]="misuse_threshold";
while storing in another variable
int source_port = Integer.parseInt(args[1]);
Just put the argument after your program name. For example
java addProgram 1 2
In your case, it should be
java YourProgramName "-s source_port_value" "-h hostname_value" "-p port_value"
These values will be received by main method in args (String array), then you can iterate the array and get the flag options and their corresponding values to proceed with your operation. I have put the double quotes to make them as a single input value. we have three arguments passing into the main method
Logic to parse the value
public static void main(String[] args){
HashMap<String,String> properties = new HashMap<String,String>();
for(int i=0;i<args.length;i++){
if(args[i].trim().startsWith("-s"))
properties.put("source_port",args[i].split(" ")[1]);
if(args[i].trim().startsWith("-h"))
properties.put("hostname",args[i].split(" ")[1]);
if(args[i].trim().startsWith("-p"))
properties.put("port",args[i].split(" ")[1]);
}
//this will give you all the property values mapped with their keys after this looping
//you can get the values from properties map from here onwards
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am building a Tetris game. I am currently debugging the game and in order to do this I need to see the values of all the variables and the variables variables and so on. With reflection I can get all a classes fields by doing this:
try
{
for(Field field : this.getClass().getDeclaredFields())
{
field.setAccessible(true);
System.out.println(field.get(this));
}
}
catch(Exception e)
{
}
What I don't know how to get all the field values of each field object.
There are two things you need to do:
Create a set of reachable objects. You don't want to recursively traverse your object graph forever.
Print values for every object.
For the first one, you need to use something like IdentityHashMap:
import java.util.IdentityHashMap;
class MyObjectCache
{
final IdentityHashSet objects = new IdentityHashSet ();
...
}
To traverse objects you can use recursive function (it is simpler, but has a stack restriction):
class MyObjectCache
{
....
void registerObject(Object o)
{
if (objects.contains(o))
{
return;
}
objects.add(o);
for(Field field : o.getClass().getDeclaredFields())
{
field.setAccessible(true);
registerObject(field.get(o));
}
}
...
}
And then you can start printing collected objects...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a text file named "hours.txt" that has lines of integers that I would like to read and copy them into an array.
The integers are the number of hours worked by 8 employees in a week. So I created a two-dimensional array with the rows being the employees and the columns being the days of the week.
public static void read()
{
Scanner read = new Scanner(new File("hours.txt"));
int[][] hours = new int[8][7];
for(int r=0; r<hours.length; r++)
{
for(int c=0; c<hours[0].length; c++)
{
while(read.hasNextInt())
{
hours[r][c]= read.nextInt();
}
}
}
}
When I try to compile this, I get the following error:
EmployeeHours.java:16: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Why is that?
Because FileNotFoundException is a checked exception. You must either catch and handle it, or throws it in the method declaration. And don't just swallow the exception; that's almost never the right way to "handle" them.
Lots more reading on exactly this topic can be found in the official Java Tutorial.
try {
//block of code
} catch (FileNotFoundException fnfe) {
}
or
public static void read() throws FileNotFoundException
The exception FileNotFoundException must be declared as part of your method signature, to tell the Java compiler that your method can throw that particular exception. You must change your method definition to:
public static void read() throws FileNotFoundException
{
... code here ...
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I don't know how to fix these errors:
class or interface expected errors
package doesn't exists
cannot find symbol
illegal start of type
cannot access java.lang
How can I better understand where the problems in my code are occurring? How can I debug these issues?
Here is my code:
import java.io.*;
public class ResourcesTesterApp {
public static void main(String[] args) {
String s1 = readLineWithResources();
String s2 = readLineWithFinally();
}
public static String readLineWithResources() {
System.out.println("Starting readLineWithResources method.");
try (RandomAccessFile in = new RandomAccessFile("products.ran", "r")) {
return in.readLine();
}} catch (IOException e) {
System.out.println(e.toString());
}
}
public static String readLineWithFinally() {
System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = null;
String s = null;
try {
in = new RandomAccessFile("products.ran", "r");
s = in.readLine();
} catch (IOException e) {
System.out.println(e.toString());
} finally {
if (in != null) {
try {
in.close();
System.out.println("RandomAccessFile closed");
} catch (IOException e) {
System.out.println("RandomAccessFile " + e.getMessage());
}
}
}
return s;
}
You question is how to better understand and debug these errors. Well all I can say is, look at the actual error message output, it will normally include a line number. Now you can look at the specific line of code and see if you can spot what is wrong.
I don't know if the formatting of the code in your question comes from a failed attempt at pasting it into stackoverflow.com or if that is also how you are working with it, but you should format it properly and that will help with spotting problems. For example, when I formatted your code above straight away you can see an additional closing curly brace.
Once you have the actual error messages and line numbers etc. your best bet is to google the error and try to understand what it means. Once you have exhausted that avenue come back here and formulate a specific question showing exactly what the error message is and the code you are running. Avoid grouping many problems into one question like you have done here.
this usually means you are writing code outside of a method.
this simply means you referenced a package that the java compiler cannot find.
this means you wrote a nonexistant variable.
this usually means you did not complete a statement, and you started writing the next one.
I dont know about this one, maybe be more specific?
I strongly suggest you take a look at the java tutorials, and follow their examples.
you can find them at http://docs.oracle.com/javase/tutorial/
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'd like to do a search for folders/directories from java, and go into those folders/directories in java. I guess it's called system utilities? Any tutorials out there, or books on the subject?
Thanks ;)
I use this code to get all ZIP files in a folder. Call this recursively checking for the file object to be a sub directory again and again.
public List<String> getFiles(String folder) {
List<String> list = new ArrayList<String>();
File dir = new File(folder);
if(dir.isDirectory()) {
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
boolean flag = false;
if(file.isFile() && !file.isDirectory()) {
String filename = file.getName();
if(!filename.endsWith(".zip")) {
return true;
}
return false;
}
};
File[] fileNames = dir.listFiles(filter);
for (File file : fileNames) {
list.add(file.getName());
}
return list;
}
You could use Apache Commons FileUtils (see: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html) and specifically the listFiles method there, which can do this recursively and use filters (so it saves you the writing of the recursion yourself and answers the search you mentioned).
If you want to navigate the file system, take a look at File and the list() method. You'll most likely require some recursive method to navigate down through the hierarchies.
I'd recommend Apache Commons IO utilities.
I don't know of any tutorials or books on that particular subject, but the way to do it is to use the java.io.File class. For example, you can use the list() to get a list of the contents of a directory. Then it's just a matter of using isDirectory() and recursing to search an entire file tree.
You can use java.io.File class to search.
here is another example:
for (File file : File.listRoots()[0].listFiles()) {
System.out.println(file);
}
the same, printing only directories:
FileFilter isDirectory = new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
};
for (File file : File.listRoots()[0].listFiles(isDirectory)) {
System.out.println(file);
}
Good example:
http://www.leepoint.net/notes-java/io/10file/20recursivelist.html
BTW. I recommend reading the whole thing. http://www.leepoint.net/notes-java/
I used Apache Commons VFS.
Is nice to use it for read contents of a directory, like this:
FileSystemManager fsManager = VFS.getManager();
FileObject path = fsManager.resolveFile( "file:///tmp" );
FileObject[] children = path.getChildren();
System.out.println( "Children of " + path.getName().getURI() );
for ( int i = 0; i < children.length; i++ )
{
System.out.println( children[ i ].getName().getBaseName() );
}
You can check if children is file, folder or something different with getType().
And same code works for reading ZIP or JAR files, FTP, SFTP, ... just changing the URL of resolveFile as you can see here.