Reputation: 15
I would like to write a general method readfile() to a class to use it on the subclasses to read all lines.
I have trouble with how to call methods from one class to another.
First, is it better to make void readfile() ? or return a File?
Secondly, which is the way to reused from other classes?
Example of my code:
public class Reader{
Scanner myReader = new Scanner(myObj);
public void readFile(){
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
}
}
public class ReadContentOfFile extends Reader{
public List<String> parseFile{
List<String> name = new ArrayList<>();
//how to get lines? as I have them, from
another method?
//for example If I want to get the
words,separated, by comma
return name;
}
}
public void Main(){
}
For example for each line of a file, how I get each element. My problem is about how to get the data for another method, for another class.
Upvotes: 0
Views: 138
Reputation: 541
Please, do not use Scanner to read a file, there are simpler and better options.
First, a File
itself it's nothing but a reference and it won't contain any content
related to the file on system. So, you can consider to return a File object only if you may need some information from the file-system about privileges, existence, perform deleting actions or retrieving path information.
Usually when i write methods to read() or save() a file i make them void.
About how do you read data and access it, in java there are a lot of possibilities.
I'll show you one pretty straightforward:
List<String> lines = Files.readAllLines(Paths.get("filename.txt"), StandardCharsets.UTF_8);
And that's it but there are more options.
Upvotes: 0
Reputation: 684
First, is it better to make void readfile() ? or return a File?
Depends on what you want to do with the output, since you are printing the contents to console then you don't have to return the file and void is OK.
But if you wanted to use this file after you call the readFile
method then you must return it or set it to class member.
Secondly, which is the way to reused from other classes? make your method static, so you can access it without creating an object since it's just a utility and object is not important here.
public static void readFile(){
//..
}
then do
Reader.readFile()
Upvotes: 1