Using openFileOutput () in the class. (not activity)

my Activity class calls another inactivity class, and when I try to use openFileOutput, my IDE tells me that openFileOutput is undefined. please, help:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.*;

import android.util.Log;
import android.content.Context;

public class testFile(){

Context fileContext;

public testFile(Context fileContext){
    this.fileContext = fileContext;
}

public void writeFile(){
    try{
            FileOutputStream os = fileContext.getApplicationContext().openFileOutput(fileLoc, Context.MODE_PRIVATE);
        os.write(inventoryHeap.getBytes()); // writes the bytes
        os.close();
        System.out.println("Created file\n");
    }catch(IOException e){
        System.out.print("Write Exception\n");
    }
}
}
+3
source share
4 answers

I deleted my answer earlier, so I was wrong, the problem I see is that you add ()to the class declaration: public class testFile(){. he must be public class testFile{. It's all.

0
source

You already have a context.

FileOutputStream os = fileContext.openFileOutput(fileLoc, Context.MODE_PRIVATE);
+2
source

Context fileContext; static Context fileContext;

0

I write this more for me than for anyone else. I am new to Android programming. I had the same problem and fixed it by passing context as a parameter to the method. In my case, the class tried to write the file to a piece of code that I found in a Java example. Since I just wanted to write the persistence of the object and did not want to worry about where the file is located, I changed it to the following:

public static void Test(Context fileContext) {
  Employee e = new Employee();
  e.setName("Joe");
  e.setAddress("Main Street, Joeville");
  e.setTitle("Title.PROJECT_MANAGER");
  String filename = "employee.ser";
  FileOutputStream fileOut =  fileContext.openFileOutput(filename, Activity.MODE_PRIVATE); // instead of:=> new FileOutputStream(filename);
  ObjectOutputStream out = new ObjectOutputStream(fileOut);
  out.writeObject(e);
  out.close();
  fileOut.close();
}

and from the calling activity, I use the following:

SerializableEmployee.Test(this.getApplicationContext());

Worked like a charm. Then I could read it (simplified version):

public static String Test(Context fileContext) {
  Employee e = new Employee();
  String filename = "employee.ser";
  File f = new File(filename);
  if (f.isFile()) {
    FileInputStream fileIn = fileContext.openFileInput(filename);// instead of:=> new FileInputStream(filename);
    ObjectInputStream in = new ObjectInputStream(fileIn);
    e = (Employee) in.readObject();
    in.close();
    fileIn.close();
   }
  return e.toString();
}
0
source

All Articles