Dan Tepper :
I've created a method which reads a file which is in the same folder as the class. I then return the text inside the file and run other methods with it.
I now need to adapt it so that the user can input a file name to be read however I am unsure on how to edit my existing code to do that. Here's what I have now.
public static String fileReader()
{
String str2 = "";
try {
Scanner sc =
new Scanner(new FileInputStream(
"C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\Untitled 2"
));
while (sc.hasNext()) {
str2 = sc.nextLine();
}
sc.close();
} catch (IOException e) {
System.out.println("No file can be found!");
}
return str2;
Any help is much appreciated!
Thanks,
Aaran
Quazan :
If you want to get user input use:
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
You can just pass fileName argument to fileReader() function and append it at the end of filepath.
String filePath = "C:\\Users\\AaranHowell\\eclipse-workspace\\UniWork\\UniWork\\src\\Assignment\\" + fileName;
Remember to specify extension to the file you want to open.
Scanner sc = new Scanner(new FileInputStream(filePath));
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=366708&siteId=1