How to call a java method so I can pass a file into the method

I want to pass a file into a java method method from the main method. Can anyone give me some help as to how I pass the file into the method - do I pass the file name ? are there any special points I need to put in the methods signature etc ?
FileReader file = new FileReader("Scores");
BufferedReader infile = new BufferedReader(file);
Where am I supposed to put the above text - in the main method or the one I want to pass the file into to?
Thanks

It's a matter of personal preference really. I would encapsulate all of the file-parsing logic in a separate class that implements an interface so that if in the future you want to start taking the integers from another source, e.g. a db, you wouldn't need to drastically alter your main application code. Probably something like this, (with an assumption that the numbers are delimited by a comma and a realisation that my file-handling routine sucks):
public class MyApp{
public static void main(String[] args){
IntegerGather g = new FileIntegerGatherer();
Integer[] result = g.getIntegers(args[0]);
public interface IntegerGatherer{
public Integer[] getIntegers(String location);
import java.io.*;
public class FileIntegerGatherer implements IntegerGatherer{
public Integer[] getIntegers(String location){
FileInputStream fs=null;
try{
File f = new File(location);
fs = new FileInputStream(f);
byte[] in = new byte[1024];
StringBuffer sb = new StringBuffer();
while((fs.read(in))!=-1){
sb.append(new String(in));
StringTokenizer st = new StringTokenizer(sb.toString(),",");
Integer[] result = new Integer[st.countTokens()];
int count = 0;
while(st.hasMoreTokens()){
result[count]=Integer.valueOf(st.nextToken());
count++;
catch(IOException e){
//something sensible here
finally{
if(fs!=null){
try{
fs.close();
catch(IOException f){
return result;
Once compiled you could invoke it as java MyApp c:\myInts.txt
Sorry if there are typos in there, I don't have an ide open ;->

Similar Messages

  • How to create power shell script to upload all termset csv files into the SharePoint2013 local taxonomy ?

    Hi Everyone,
    I want to create a powershell script file
    1) Check a directory and upload all termset csv files into the SharePoint local taxonomy.
    2) Input paramaters - directory that containss termset csv files, Local Termstore to import to,
    3) Prior to updating get a backup of the existing termstore (for rollback/recovery purposes)
    4) Parameters should be passed in via XML file.
    Please let me know how to do it.
    Regards,
    Srinivas

    Hi,
    Please check this link
    http://termsetimporter.codeplex.com/
    Please remember to click 'Mark as Answer' on the answer if it helps you

  • How can I put files into the trash without login every time?

    Every time I want to put items in the trash, after dragging things to the basket, I have to sign in.  Why? Can I set the defaul to allow me to do so without login?

    The procedure below will reset the permissions of a user's home folder in OS X 10.7.4 or later, including 10.8 or later. If you're running an earlier version of 10.7, update to the latest version first. This procedure should not be used under OS X versions older than 10.7.4.
    Back up all data before you begin.
    Step 1
    Click the Finder icon in the Dock. A Finder window will open.
    Step 2
    Press the following key combinations, in the order given:
    Command-3
    Shift-command-H
    Command-I (the letter "I" as in "Info.")
    The Info window of your home folder will open.
    Step 3
    Click the lock icon in the lower right corner and authenticate with the name and login password of an administrator on the system. If you have only one user account, you are the administrator.
    Step 4
    In the Sharing & Permissions section of the window, verify that you have "Read & Write" privileges. If not, use the "+" and "-" buttons in the lower left corner to make the necessary changes.
    Step 5
    By default, the groups "staff" and "everyone" have "Read Only" privileges. With those settings, the files at the top level of your home folder will be readable by other local users. You can change the privileges to "No Access" if you wish, but then your Public and Drop Box folders will be inaccessible to others. Most likely, you don't need to change these settings.
    Step 6
    If there are entries in the Sharing & Permissions list for users or groups other than "me," "staff," and "everyone," delete them.
    Step 7
    Click the gear icon at the bottom of the Info window and select Apply to enclosed items... from the drop-down menu. Confirm. The operation may take several minutes to complete. When it does, close the Info window.

  • How to call a Java method in a C consoleapplication?

    I have to call a void method of a javaclass using a c consoleapplication. No argument are passed to it.
    I can't make an object of that class..
    This is my implementation in c (using JNI):
    void update(void)
         classn = "<name>";
         cls = (*env) ->FindClass(env, classn );
         if (cls == 0)
    printf(" Can't find class %s\n", classn );
         mid =
    (*env)->GetMethodID(env, cls, "<methodname>", "()V");
         (*env)->CallVoidMethod(obj, env ,m id);
    This goes wrong...
    The problem is that I have no jobject (obj) of the class, because I don't want one...I don't need one. How can I call that void method without an object and only using the classname..??

    You have to make the java method a static method, and use CallStaticVoidMethod.
    "static" means that the method belongs to the class, and not an object of that class.

  • How to call a java method in a Stored procedure

    Hi.,
    I was trying to call a method in a stored procedure
    This was my procedure
    CREATE OR REPLACE PROCEDURE proc_copy_file(sr_file VARCHAR2,dt_file VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'FileCopy.copyfile(String,String)'; // calling a java method
    /   this was my java method
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "FileCopy" as
    import java.io.File;
      import java.io.IOException;
      import java.io.FileReader;
      import java.io.FileWriter;
      import javax.imageio.stream.FileImageInputStream;
      import javax.imageio.stream.FileImageOutputStream;
      import java.security.AccessControlException;
      public class FileCopy {
          // Define variable(s).
              private static int c;
              private static File file1,file2;
              private static FileReader inTextFile;
              private static FileWriter outTextFile;
              private static FileImageInputStream inImageFile;
              private static FileImageOutputStream outImageFile;
              // Define copyText() method.
              public static void copyfile(String fromFile,String toFile) throws AccessControlException
                // Create files from canonical file names.
                file1 = new File(fromFile);
                file2 = new File(toFile);
                // Copy file(s).
                try
                  // Define and initialize FileReader(s).
                  inTextFile  = new FileReader(file1);
                  outTextFile = new FileWriter(file2);
                  // Read character-by-character.
                  while ((c = inTextFile.read()) != -1) {
                    outTextFile.write(c); }
                  // Close Stream(s).
                  inTextFile.close();
                  outTextFile.close(); }
                catch (IOException e) {
                  System.out.println ("-------"); }
             // return 1;
          public static void main(String[] args){
                          switch(args.length){
                                  case 0: System.out.println("File has not mentioned.");
                                                  System.exit(0);
                                  case 1: System.out.println("Destination file has not mentioned.");
                                                  System.exit(0);
                                  case 2: copyfile(args[0],args[1]);
                                                  System.exit(0);
                                  default : System.out.println("Multiple files are not allow.");
                                                    System.exit(0);
    };while i am executing this method i m getting error as
    ORA-29531: NO METHOD COPYFILE IN CLASS FILECOPY
    ORA-06512: AT "RMVER721.PROC_COPY_FILE", LINE 1could anyone help me

    Looks like it is a matter of not quite the same namespace for String object.
    I can get it to work by the java source containing:
              public static void copyfile(java.lang.String fromFile,java.lang.String toFile) throws AccessControlExceptionAnd the PL/SQL source:
    NAME 'FileCopy.copyfile(java.lang.String,java.lang.String)'; // calling a java methodSeems like when you just use "String", then the namespace resolving in the java source is not the same as the namespace resolving in the PL/SQL?
    Addendum:
    You do not need to put java.lang.String in the java source, String will do (java.lang is by default "imported"?)
    But in the PL/SQL source java.lang namespace prefix is needed - java.lang is not "imported" here.
    Edited by: Kim Berg Hansen on Nov 23, 2011 1:07 PM

  • How to call a Java class from another java class ??

    Hi ..... can somebody plz tell me
    How to call a Java Class from another Java Class assuming both in the same Package??
    I want to call the entire Java Class  (not any specific method only........I want all the functionalities of that class)
    Please provide me some slotuions!!
    Waiting for some fast replies!!
    Regards
    Smita Mohanty

    Hi Smita,
    you just need to create an object of that class,thats it. Then you will be able to execute each and every method.
    e.g.
    you have developed A.java and B.java, both are in same package.
    in implementaion of B.java
    class B
                A obj = new A();
                 //to access A's methods
                 A.method();
                // to access A's variable
                //either
               A.variable= value.
               //or
               A.setvariable() or A.getvariable()

  • How to pass a file into a java method

    I am trying to pass a file into a java method so I can read the file from inside the method. How can I do this? I am confident passing int, char, arrays etc into methods as I know how to identify them in a methods signature but I have no idea how to decalre a file in a mthods signature. Any ideas please ?
    Thanks

    Hi,
    Just go thru the URL,
    http://www6.software.ibm.com/devtools/news1001/art24.htm#toc2
    I hope you will get a fair understanding of 'what is pass by reference/value'.
    You can pass Object reference as an argument.
    What Pablo Lucien had written is right. But the ideal situation is if you are not modifying the
    file in the calling method, then you can pass the String (file name) as an argument to the called method.
    Sudha

  • How to call a java program in javafx class(Urgent) and even vice versa

    Hi all,
    Here I have two questions:
    1)
    Please let me know how to call a javafx in java program...
    I tried with the following code but it is not working..
    The below is the java program in which I made a call to the Fx program.
    FxMainLauncher.java
    import net.java.javafx.FXShell;
    public class FxMainLauncher {
    public static void main(String[] args) throws Exception {
    FXShell.main(new String[] {"HelloWorld.fx"});
    2) How to call a java program in javafx class
    Here is my javafx program
    import check.*;
    import javafx.ui.*
    var instance = new MyJava();
    //visible:true
    System.out.println("Number is: {instance}");
    Here is my java program
    public class MyJava {
    public static void main(String args[])
    System.out.println("JAVAFX TO JAVA");
    Even this is not working please let me know ASAP
    Thanks in advance,
    V.Srilakshmi

    GOT IT !!!
    I had to change the name of the method in .h file generated by javah command. On doing
    javac -d ../../classes HelloWorld.java
    go to the ../../classes directory (where you have the class file) and do
    javah HelloWorld
    I got a HelloWorld.h file in which I had
    JNIEXPORT void JNICALL Java_HelloWorld_display(JNIEnv *, jobject);
    I added the package name too:
    JNIEXPORT void JNICALL Java_GUI_HelloWorld_display(JNIEnv *, jobject);
    The HelloWorldImp.c file should have the same name (ie with package) and be in the same directory(ie ../../classes)
    compile and build the shared library to get "libhello.so" file
    gcc -c -fPIC -I/usr/lib/j2sdk1.3/include -I/usr/lib/j2sdk1.3/include/linux HelloWorldImp.c
    gives .o file
    gcc -shared -o libhello.so HelloWorldImp.o
    gives .so file
    then run java with the command in my first message. It works.
    Thanks for the reply "thedracle".

  • How to call a java script in while eventprocessing?

    hi friends,
    How to call a java script from an event.
    when i click a button, i want to display a message in IE.
    For ex: BTN_CAN,
    When i click on this in IE i want show a message like "clicked on cancelled".
    how can i do this.....
    in javascript WINDOW.ALERT i am trying....
    Regards,
    Shankar.

    you can do some thing like this...
    < % @  pa g e la ng uag  e="a b ap" %>
    < % @ e xte n sion name="htmlb" prefix="h tm l b"  %  >
    <  h t  m l b:co  nt e nt d es ign="design2 00  3"  >
      <  ht m lb:page title=" "    >
        <  h tm lb :for m  >
           < h t  mlb:textVi ew text   = "Hello World!"
                          des  ign = "EMPHASIZED" />
          < ht  m lb  :bu  tton text          = "Press Me"
                         on  Clie  ntC lick = "al ert(' H ell  w or l d')"  / >
        <  / h t mlb  :for m >
      < / ht mlb :pa g e >
    <   / htm lb:co nt e nt >
    Edited by: Vijay Babu Dudla on Oct 6, 2008 7:20 AM

  • How to call a java script?

    Hi,
    I m new to Indesign and also to MAC OS...
    I ve tried the sdk samples of InDesign CS3 on MAC OS. It works well.
    I m making changes to one of the samples (BasicPanel). I ve added few check boxes and buttons in it. I donno where to give the code for button(in the panel) event/action?
    I also need to know "how to call a java script from InDesign CS3 SDK ?"...
    I have the Scripts ready... Can someone provide the code used to call JS...
    Someone pls help me.....
    Thank You...

            Here s the code to call a Javascript:
            IDFile scriptFile;
            FileUtils::GetAppInstallationFolder(&scriptFile);                    //application folder path
            FileUtils::AppendPath(&scriptFile, PMString("Scripts", -1, PMString::kNoTranslate));               
            FileUtils::AppendPath(&scriptFile, PMString("Scripts Panel", -1, PMString::kNoTranslate));
            //inside the scripts panel, append path of the folder in which ur script is present.
            //Suppose, ScriptsPanel->NewFolder->Link.jsx
            FileUtils::AppendPath(&scriptFile, PMString("NewFolder", -1, PMString::kNoTranslate)); 
            FileUtils::AppendPath(&scriptFile, PMString("Link.jsx", -1, PMString::kNoTranslate));
            InterfacePtr<IScriptRunner>scriptRunner(Utils<IScriptUtils>()->QueryScriptRunner(scriptFi le));
            bool filestatus=scriptRunner->CanHandleFile(scriptFile);
            if(filestatus==1)
                scriptRunner->RunFile(scriptFile,kTrue,kFalse);
    Regards,
    tnhems

  • How to: Calling a java class from asp?

    Hello all i have a problem to call a Java class from a asp
    Here what I do:
    [JavaSays.java]
    package JavaCom;
    public class JavaSays
    public String Hello()
    return "Hello world" ;
    then
    javareg /register /class:JavaCom.JavaSays /progid:JavaCom.JavaSays
    md c:\winnt\Java\TrustLib\JavaCom
    copy JavaSays.class c:\winnt\Java\TrustLib\JavaCom
    --Asp
    --TestJavaCom.asp
    <html>
    <body>
    <h1>Simple Test</h1>
    <% Set ObjPrueba = Server.CreateObject("JavaCom.JavaSays") %>
    <%= ObjPrueba.SimpleFn(5) %>
    <hr>
    </body>
    </html>
    when i try to run my asp
    it tell me that:
    Error type : Server Objetc, ASP 0177 (0x80040111)
    ClassFactory can not find the class
    any idea???
    thanks.

    I think the OP wants to use a class file as a COM object. I've never done that, but this URL:
    http://support.microsoft.com/default.aspx?scid=KB;EN-US;q167941&
    seems to indicate that you should have placed the class file into the c:\winnt\Java\TrustLib\ sub directory before you ran the JAvaReg bat file - I would re-run JavaReg and bounce IIS and associated services and see if that works out.
    Good Luck
    Lee

  • How do I disable those pesky "hover-over" pop ups? I tried the method of right clicking on them and opting out, but it doesn't work. If you guys could add some kind of blocker to your browser, it would be a huge plus!

    # Question
    How do I disable those pesky "hover-over" pop ups? I tried the method of right clicking on them and opting out, but it doesn't work. If you guys could add some kind of blocker to your browser, it would be a huge plus!

    Chris CA wrote:
    Did you createa smart playlist? It's purple with a gear icon.
    And you set the criteria to
    Match rule:
    Date added is in the last two weeks?
    I tried it, but couldn't get it to work. I think I had trouble with the Rule. I put a Rule in as follows: Data added in the last five hours? I added music (data) but nothing appeared in my Smart Playlist. Oh yes - I named the playlist: Recently Added.
    What did I do wrong? Is it necessary to have a question mark at the end of the Rule? I couldn't find anything on how to create a Smart Playlist in Help. There is stuff in there, but it does not go into much detail, i.e., nothing on the proper wording of the Rule.

  • How do I add a jar file into the build path of the compiler?

    Hey,
    I'm trying to import a jar file into the build path of the compilation process, but it does not find the packages or the classes that are in it.
    I think I don't add it right...
              ArrayList<String> options=new ArrayList<String>();
              options.add("-d");
              options.add(targetDirectory);
              options.add("-classpath");
              for(String str:includeDirectory)
                   options.add(str);
              if (!compiler.getTask(writer, fileManager, diagnostics, options, classes, compilationUnits).call());
                    ....and I've tried this way:
         public void setTargetDirectory(String targetDirectory) {
              this.targetDirectory = "-d " + targetDirectory;
         private void compile(Iterable<? extends JavaFileObject> compilationUnits) throws Exception {
              ArrayList<String> options = new ArrayList<String>();
              options.add(targetDirectory);
              String classPath="-cp ";// tried this also with "-classpath"
              for (String str : includeDirectory)
                   classPath+=str+":";
              options.add(classPath);
         if (!compiler.getTask(writer, fileManager, diagnostics, options, classes, compilationUnits).call())
              // throw new Exception("Compilation Error");
         }Thanks in advance,
    Adam.
    Edited by: Adam-Z. on Feb 24, 2010 5:41 AM
    Edited by: Adam-Z. on Feb 24, 2010 5:42 AM

    Thank you for your reply,
    Q: Are there .class files in that directory in that jar file? (the compiler doesn't ( can't )) look for directories, it can just look for specific files , and scan to get a list of all files matching certain criteria. So if there are no class files, it will say the package doesn't exist, even if there is a directory, possibly containing other files.yes there are class files in the jar, the tree structure:
    j2MeDataChunkGenerator_Plugin\(lots of class files)
    META-INF\manifest.mf
    and thats it.
    , your code will only work on windows because other platforms use a different path separator. You should use java.io.File.pathSeparator not explicit ';" when building your classpath. (this is unrelated to your problem, but you should correct it)will do, thanks.
    Q: Is that error in your post formatted by your own diagnostics? (we could possibly help you better if we didn't have to guess!!)I would not post my own error code, this text is generated by the compiler diagnostic.
    {code}
         System.err.println(" Error details: " + diagnostic.getMessage(null));
    {code}
    Q: Is line 3 of ImageCroper_Editor.java (sic) an import statement? (we could possibly help you better if we didn't have to guess!!)it is an import error... didn't the error message stated that it is an import problem? wired, I'm sure before it did. anyway it is an import error.
    Also you don't show us what the variable includeDirectory is in terms of type, and contents, that might be helpful. (we could possibly help you better if we didn't have to guess!!)It has only one String object: "D:\%Important Documents\WorkSpaces\PacMan\ApplicationManager\Plug-in\Data Chunk Designer.jar"
    the last file on the classpath list.
    Q: Have you proven this? that i did post, in this long line of text.
    Q: Is the compiler finding other classes (in other packages) in that same jar file?No. all the class files are in the jar, they all have entries that start with "j2MeDataChunkGenerator_Plugin\*.class", and since I get 47 errors I guess it does not load any other class.
    thank you for you comments, the problem with having these errors, is that I can't even get a piece of information where this error is coming from, only that it is an import loading error package not found, what does that mean? that the jar was not loaded in compilation(no error about this), that the jar is corrupted(no error about this), that the path is incorrect(it is correct I made sure), that there is no such package in the jar(There is), that the compiler does not load the package(does it even do that?), really I can't even guess why this happens, I've been at this on and of all day today, really annoying.
    Thanks,
    Adam.

  • How to import an .csv file into the database?

    and can we code the program in JSP to import the.csv file into the database.

    It is better to use Java class to read the CSV file and store the contents in the database.
    You can use JSP to upload the CSV file to the server if you want, but don't use it to perform database operations.
    JSPs are good for displaying information on the front-end, and for displaying HTML forms, there are other technologies more suitable for the middle layer, back end and the database layer.
    So break you application into
    1) Front end - JSPs to display input html forms and to display data retrieved from the database.
    2) Middle layer - Servlets and JavaBeans to interact with JSPs. The code that reads the CSV file to parse it's contents should be a Java Class in the middle layer. It makes use of Java File I/O
    3) Database layer - Connects to the database using JDBC (Java Database Connectivity), and then writes to the database with SQL insert statements.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Keeping the above concepts in mind, first build a simple JSP and get it to work,
    then research on Google , for Java File I/O , discover how to read a file,
    Then search on how to readh a CSV file using Java.
    After researching you should be able to read the CSV file line by line and store each line inside a Collection.
    Then research on Google, on how to write to the database using JDBC
    Write a simple program that inserts something to a dummy table in the database.
    Then, read the data stored in the Collection, and write insert statements for each records in the collection.

  • Pass an arrayList into a method

    I am looking to pass and  arraylist into a method and I am wondering how this is done...

    I figured it out:
    public function someMethod(someArray:ArrayList){}
    I figured it was the same.
    This is dealing with flex, How ever on the AS side, so its a pure AS question

Maybe you are looking for