Tyler Richardson
Tyler Richardson

Reputation: 71

Using a separate java files methods

This question is about Android, although i dont think that this is android-specific.

I have a project that i want to use two files with: MainActivity.java and filetools.java . I have three methods in filetools.java, read, write and append. I want to be able to do something like this in my MainActivity:

filetools.write("/sdcard/file.txt", "something");

The code for MainActivity is just the package, imports, the class, and onCreate.

The code for filetools:

package com.tylerr147.FileRW;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class filetools
{
      public String read(String fName){
       try{
          File mFile = new File(fName);
          String content = new Scanner(mFile).useDelimiter("\\Z").next();
      return content;
    }catch(Exception e) {
      return "There was an error retrieving your file. The proccess returned this error:\n"+e.toString();
    }

  }

  public boolean write(String loc, String stuff) {
    File mfile = new File(loc);
    try {
      mfile.createNewFile();
      FileOutputStream f = new FileOutputStream(mfile);
      OutputStreamWriter f2 = new OutputStreamWriter(f);
      f2.append(stuff);
      f2.close();
      f.close();
    } catch(IOException e) {
      return false;
    }
    return true;
  }

  public void append(String filename,     String content) {
    write(filename, read(filename)+content);
  }
}

Another thing i would like to be able to do is to have a completely different app by the package com.app.importer

how could i do something like

import com.app.importer;

importerAppsMethod();

I have found a few posts on stackoverflow, but they do not help.

Importing my custom class and calling it's method?

There are a few more, and i have searched and can not find anything that works for me. Any help is appreciated

Upvotes: 0

Views: 96

Answers (1)

Tyler Richardson
Tyler Richardson

Reputation: 71

I am putting @ishmaelMakitla comment intocan answer.

To do something like filetools.write("/sdcard/file.txt", "something"); - you need to declare the write method as static. For example: public static boolean write(String loc, String stuff). You may have to do the same for all other methods if you want similar behavior. Is this what you are looking for?

Upvotes: 2

Related Questions