#Find a specific .txt file inside a folder
1 messages · Page 1 of 1 (latest)
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
Scanner sc = new Scanner(System.in);
// file path from the files folder rather than putting
// it to the root folder.
String filePath = "src/main/java/org/example/files";
System.out.println("Who would you want to search for?");
String userInputfileName = sc.nextLine();
try (Scanner file = new Scanner(Path.of(filePath))) {
// logic
// TODO if userInputfilenName is equal to
// (.txt file from inside the filePath)
if (userInputfileName.equals(filePath)) {
//we read the file until all lines have been read
while (file.hasNext()) {
// we read one line
String row = file.nextLine();
// we print the line that we read
System.out.println(row);
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}```
Detected code, here are some useful tools:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// file path from the files folder rather than putting
// it to the root folder.
String filePath = "src/main/java/org/example/files";
System.out.println("Who would you want to search for?");
String userInputfileName = sc.nextLine();
try (Scanner file = new Scanner(Path.of(filePath))) {
// logic
// TODO if userInputfilenName is equal to
// (.txt file from inside the filePath)
if (userInputfileName.equals(filePath)) {
//we read the file until all lines have been read
while (file.hasNext()) {
// we read one line
String row = file.nextLine();
// we print the line that we read
System.out.println(row);
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
I think the typical logic is just to get the file's name from the user (so in your case song.txt), then to loop over the Files inside the "files" directory and if any such File is named song.txt, to just print out its contents.
Does that help?
So first, don't put non java files in java folder
Either put them in resources or in the project root or another non project place
Second, if you want to read from java or resources folders, then you must use Class#getResourceAsStream
Third, what are you trying to do by reading a file ?
thanks , i just want to print what’s inside the file just for practice
Then note that files in resources should only be resources, like images, text, etc that you use in your app, and you can't write to resources