2

This is a simple question with probably a simple answer but I can't seem to find the answer anywhere else.

I have an input file that I open up and do various things with using RandomAccessFile in one class. I would like to pass that file onto another class so it can do various things with it as well. I'm not sure how this would be done however.

Gasper Gulotta
  • 159
  • 3
  • 9
  • Simple. Have one class have it as in instance (or static, depending on your case) variable, and pass it as a parameter to the other method in the other class. – gparyani Jun 04 '13 at 17:18
  • How does a method take a file as a parameter in Java? – Gasper Gulotta Jun 04 '13 at 17:20
  • 1
    @Downvoter This is a good question and should be preserved for future reference (say, by intro Java students). – gparyani Jun 04 '13 at 17:23

3 Answers3

1

Use a setter and pass the instance of the RandomAccessFile to the second class instance

myClassInstance.setFile(RandomAccessFile myFile);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • @Downvoter This makes perfect sense (in fact, it is a good idea to have two references in two different classes referring to the same object). – gparyani Jun 04 '13 at 17:22
  • 1
    @GasperGulotta you can't be downvoter yet because you need 125 rep atleast to downvote – pinkpanther Jun 04 '13 at 18:52
0

Maybe you should use Singleton design pattern. Then you could access file across many places with Singleton.getInstance().write("smth");

jtomaszk
  • 9,223
  • 2
  • 28
  • 40
0

Make the file a parameter to a method or constructor of the other class. For example

public void displayFirstLine (RandomAccessFile myFile) {
    //your code here
}
Aaron Kurtzhals
  • 2,036
  • 3
  • 17
  • 21