Incorporating file input and file output into a java program

Watch
Carrying a torch
Badges: 9
Rep:
?
#1
Report Thread starter 4 weeks ago
#1
Hmm, suppose I have a record and it holds trigger words. Is it possible to change these values manually? Yes. Is it however possible to change the values into something from an inputted file? That is have a .txt file containing trigger words so that different text-files-containing-trigger-words-about-a-specific-topic are read only when appropriate to do so i.e. when the user does something to initiate it.
0
reply
Carrying a torch
Badges: 9
Rep:
?
#2
Report Thread starter 4 weeks ago
#2
(Original post by Carrying a torch)
Hmm, suppose I have a record and it holds trigger words. Is it possible to change these values manually? Yes. Is it however possible to change the values into something from an inputted file? That is have a .txt file containing trigger words so that different text-files-containing-trigger-words-about-a-specific-topic are read only when appropriate to do so i.e. when the user does something to initiate it.
Also, if you sort of understand what I am trying to reach with this program, how can I then output either the trigger words file or any other file really
0
reply
Strange5050
Badges: 16
Rep:
?
#3
Report 4 weeks ago
#3
(Original post by Carrying a torch)
Hmm, suppose I have a record and it holds trigger words. Is it possible to change these values manually? Yes. Is it however possible to change the values into something from an inputted file? That is have a .txt file containing trigger words so that different text-files-containing-trigger-words-about-a-specific-topic are read only when appropriate to do so i.e. when the user does something to initiate it.
You’ll need import file.io and file.fileNotFoundException into your project for this. I’ll show you how to read and write to file, and you’ll be able to figure out how to implement this to fit your needs.

Code:
try {
      File myFile = new File("YoureFileName.txt");
      Scanner myScanner = new Scanner(myFile);

      while (myReader.hasNextLine()) {
        String data = myScanner.nextLine();
        System.out.println(data);
      }
      myScanner.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
    }
myScanner.close();
You’ll need to use a try catch here, otherwise if the file does or exist it will end your entire program with an unhandled exception. For writing to files you’ll need to import FileWrite and IOException.

Code:
try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("I’m writing to files");
      myWriter.close();
    } catch (IOException e) {
      System.out.println("An error occurred.");
    }
That’s assuming the file already exists. If it doesn’t and you want to create a file, then you do it using:

Code:
try {
      File myFileCreator = new File("MyFile.txt");
      if (myFileCreator.createNewFile()) {
        System.out.println("File created”);
      }
    } catch (IOException e) {
      System.out.println("An error occurred”);
    }
I advise you to read the documentation on these classes to understand everything you can do with them.
Last edited by Strange5050; 4 weeks ago
0
reply
Carrying a torch
Badges: 9
Rep:
?
#4
Report Thread starter 4 weeks ago
#4
(Original post by Strange5050)
You’ll need import file.io and file.fileNotFoundException into your project for this. I’ll show you how to read and write to file, and you’ll be able to figure out how to implement this to fit your needs.

Code:
try {
      File myFile = new File("YoureFileName.txt");
      Scanner myScanner = new Scanner(myFile);

      while (myReader.hasNextLine()) {
        String data = myScanner.nextLine();
        System.out.println(data);
      }
      myScanner.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
    }
myScanner.close();
You’ll need to use a try catch here, otherwise if the file does or exist it will end your entire program with an unhandled exception. For writing to files you’ll need to import FileWrite and IOException.

Code:
try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("I’m writing to files");
      myWriter.close();
    } catch (IOException e) {
      System.out.println("An error occurred.");
    }
That’s assuming the file already exists. If it doesn’t and you want to create a file, then you do it using:

Code:
try {
      File myFileCreator = new File("MyFile.txt");
      if (myFileCreator.createNewFile()) {
        System.out.println("File created”);
      }
    } catch (IOException e) {
      System.out.println("An error occurred”);
    }
I advise you to read the documentation on these classes to understand everything you can do with them.
In particular for file input (where you're reading the .txt file) is it possible to have my reader only read the last two lines of my text file? In other words, how can we get contorl over what part of the .txt file is read? thanks
0
reply
Carrying a torch
Badges: 9
Rep:
?
#5
Report Thread starter 4 weeks ago
#5
(Original post by Strange5050)
You’ll need import file.io and file.fileNotFoundException into your project for this. I’ll show you how to read and write to file, and you’ll be able to figure out how to implement this to fit your needs.

Code:
try {
      File myFile = new File("YoureFileName.txt");
      Scanner myScanner = new Scanner(myFile);

      while (myReader.hasNextLine()) {
        String data = myScanner.nextLine();
        System.out.println(data);
      }
      myScanner.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
    }
myScanner.close();
You’ll need to use a try catch here, otherwise if the file does or exist it will end your entire program with an unhandled exception. For writing to files you’ll need to import FileWrite and IOException.

Code:
try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("I’m writing to files");
      myWriter.close();
    } catch (IOException e) {
      System.out.println("An error occurred.");
    }
That’s assuming the file already exists. If it doesn’t and you want to create a file, then you do it using:

Code:
try {
      File myFileCreator = new File("MyFile.txt");
      if (myFileCreator.createNewFile()) {
        System.out.println("File created”);
      }
    } catch (IOException e) {
      System.out.println("An error occurred”);
    }
I advise you to read the documentation on these classes to understand everything you can do with them.
I have a user log that currently gets written to whenever the user enters their name at the start of using my program. It also writes the time they use it. I am trying to read this file in such a way where before the program is used by a new person they are told who the previous person to use it was, if that makes sense.
0
reply
Strange5050
Badges: 16
Rep:
?
#6
Report 4 weeks ago
#6
(Original post by Carrying a torch)
In particular for file input (where you're reading the .txt file) is it possible to have my reader only read the last two lines of my text file? In other words, how can we get contorl over what part of the .txt file is read? thanks
Unless you know specifically how many lines are in that file. There is of course the option to overwrite file. Meaning the only line or two is that of the previous user, and you know that.

Otherwise you could get all the lines in the file, save to a list, and from there do your search/indexing. E.g.

Code:
List<String> lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8);
lines.get(0); // Grabs the first index.
Or use something like (if you know exactly what line):
Code:
String line = Files.readAllLines(Paths.get("MyFile.txt")).get(YourLineNumberHere)
0
reply
Carrying a torch
Badges: 9
Rep:
?
#7
Report Thread starter 4 weeks ago
#7
(Original post by Strange5050)
Unless you know specifically how many lines are in that file. There is of course the option to overwrite file. Meaning the only line or two is that of the previous user, and you know that.

Otherwise you could get all the lines in the file, save to a list, and from there do your search/indexing. E.g.

Code:
List<String> lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8);
lines.get(0); // Grabs the first index.
Or use something like (if you know exactly what line):
Code:
String line = Files.readAllLines(Paths.get("MyFile.txt")).get(YourLineNumberHere)
With both the examples of code you have given isn't there the assumption that it is known how many users have so far written their names (i.e. how many lines exist)? If that be by writing a line number or grabbing an index posiition. I wouldn't really have this information unless there exists something like array.length where the whole thing is searched but even then it isn't the last two lines of my text file, hmm
0
reply
Carrying a torch
Badges: 9
Rep:
?
#8
Report Thread starter 4 weeks ago
#8
(Original post by Carrying a torch)
With both the examples of code you have given isn't there the assumption that it is known how many users have so far written their names (i.e. how many lines exist)? If that be by writing a line number or grabbing an index posiition. I wouldn't really have this information unless there exists something like array.length where the whole thing is searched but even then it isn't the last two lines of my text file, hmm
Actually I guess I would have to just find a way of getting total number of lines and then make use of code similar to yours because it would be a lot easier if I know the length of my .txt file
0
reply
Strange5050
Badges: 16
Rep:
?
#9
Report 4 weeks ago
#9
(Original post by Carrying a torch)
Actually I guess I would have to just find a way of getting total number of lines and then make use of code similar to yours because it would be a lot easier if I know the length of my .txt file
My first example with the list, you could easily iterate the last index as it represent every line in the file. The other method, you couldn't.
0
reply
Carrying a torch
Badges: 9
Rep:
?
#10
Report Thread starter 4 weeks ago
#10
(Original post by Strange5050)
My first example with the list, you could easily iterate the last index as it represent every line in the file. The other method, you couldn't.
I'm not very familiar with lists. In "lines.get(0)", wouldn't the 0 be another way of stating which line of text to get?

My plan now is to create a while loop that checks if my text file has a next line and while it does it should add to a counter called numberOfLines, like this:

while (myFile.hasNextLine()) {
NumberOfLines++;
}


However, I keep getting this error so I need to check my lines of code before it:

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.base/java.util.Scanner.ensureOpen(Sca nner.java:1150)
at java.base/java.util.Scanner.findWithinHori zon(Scanner.java:1781)
at java.base/java.util.Scanner.hasNextLine(Sc anner.java:1610)
at HB.main(HB.java:65)

Process finished with exit code 1
0
reply
Strange5050
Badges: 16
Rep:
?
#11
Report 4 weeks ago
#11
(Original post by Carrying a torch)
I'm not very familiar with lists. In "lines.get(0)", wouldn't the 0 be another way of stating which line of text to get?

My plan now is to create a while loop that checks if my text file has a next line and while it does it should add to a counter called numberOfLines, like this:

while (myFile.hasNextLine()) {
NumberOfLines++;
}


However, I keep getting this error so I need to check my lines of code before it:

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.base/java.util.Scanner.ensureOpen(Sca nner.java:1150)
at java.base/java.util.Scanner.findWithinHori zon(Scanner.java:1781)
at java.base/java.util.Scanner.hasNextLine(Sc anner.java:1610)
at HB.main(HB.java:65)

Process finished with exit code 1
Don't use the File object 'myFile' to see if there's a next line. You need to use the object that you are reading the file with to do this. E.g.

Code:
BufferedReader reader = new BufferedReader(new FileReader("MyFile.txt"));
int lines = 0;
while (reader.readLine() != null) { 
    lines++;
}
reader.close();
The File object doesn't have a method called 'hasNextLine'. In this case, the reader will return null once there is no more lines. Thus you can use this to mark the end of the file.

'HasNextLine()' is a method from the Scanner class. Which, depending on the way you choose to read file could work as well. But you'd need to create a Scanner object.

Edit: Posting on TSR can be quite slow and cumbersome sometimes. If you have Discord etc.. and would prefer to get faster responses just PM your Discord username or such. Otherwise no problem.
Last edited by Strange5050; 4 weeks ago
0
reply
Carrying a torch
Badges: 9
Rep:
?
#12
Report Thread starter 4 weeks ago
#12
(Original post by Strange5050)
Don't use the File object 'myFile' to see if there's a next line. You need to use the object that you are reading the file with to do this. E.g.

Code:
BufferedReader reader = new BufferedReader(new FileReader("MyFile.txt"));
int lines = 0;
while (reader.readLine() != null) { 
    lines++;
}
reader.close();
The File object doesn't have a method called 'hasNextLine'. In this case, the reader will return null once there is no more lines. Thus you can use this to mark the end of the file.

'HasNextLine()' is a method from the Scanner class. Which, depending on the way you choose to read file could work as well. But you'd need to create a Scanner object.

Edit: Posting on TSR can be quite slow and cumbersome sometimes. If you have Discord etc.. and would prefer to get faster responses just PM your Discord username or such. Otherwise no problem.
I should have clarified. I assigned my reader to 'myfile'. And yes, I was initially using hasNextLine because I thought it would be okay to use if I had an ordinary scanner as my reader.

everything seems to be working fine now just code cleanup needed, thanks!

Sadly, I don't really use discord
1
reply
X

Quick Reply

Attached files
Write a reply...
Reply
new posts
Back
to top
Latest
My Feed

See more of what you like on
The Student Room

You can personalise what you see on TSR. Tell us a little about yourself to get started.

Personalise

Are you travelling in the Uni student travel window (3-9 Dec) to go home for Christmas?

Yes (96)
28.49%
No - I have already returned home (44)
13.06%
No - I plan on travelling outside these dates (63)
18.69%
No - I'm staying at my term time address over Christmas (34)
10.09%
No - I live at home during term anyway (100)
29.67%

Watched Threads

View All