I have made a code of which gets a bunch of data from different files in a folder, I have then made sure to only look for a certain kind of word in the files. Then I have made sure the code prints out the results in the console.
All the things I have done up till now works perfectly, but here comes the issue. I want the code to also print/write the information to a .txt file. This sort of works, but it only prints one of the many lines from the different files. I am completely sure that there are more that one as the console print shows at least 20 different lines containing the right word.
I am not completely sure where I have gone wrong, I have also tried to add the .flush(); right before the .close(); but it still wont work. I have also tried to add the pToDocu.close(); underneath the sc.close();, but that doesn't work either, as that doesn't even write anything, that just creates a blank file.
So in short the code is supposed to write a bunch of lines, but it only writes one.
public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#"))
{
System.out.println(s);
pTD.println(s);
pTD.close();
}
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
UPDATE
I have changed the code to now have the pTD.close(); outside of the while loop like seen below. Only issue is that the file which is created now is blank, it has no information inside it.
public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#"))
{
System.out.println(s);
pTD.println(s);
}
}
sc.close();
pTD.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You are closing the file (pTD) after the first time you write to it. You should extract the close() call from the loop and move it after it:
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#")) {
System.out.println(s);
pTD.println(s);
}
}
sc.close();
pTD.close();
Remove
pTD.close();
from your while loop. You close your Print Writer after the first write
It looks like you want to commit ALL of those records to your PrintWriter. Therefore, your pTD.close(); needs to be outside of your for loop, since you declared the PrintWriter before your for loop.
Related
I am writing simple program that is looking for file and if it exists, writes his path to txt file. If not, program is freezed for 1 minute. My problem is that file path is not being printed into txt file when searched file exists. I think it is something wrong with try block. I do not know where the problem is. How can i solve it?
public class FileScanner {
public void scanFolder() throws IOException, InterruptedException {
Scanner input = new Scanner(System.in);
//tworzenie pliku logu
File log = new File("C:/Users/mateu/OneDrive/Pulpit/log.txt");
if (!log.exists()) {
log.createNewFile();
}
//obiekt zapisujacy nazwy i sciezki plikow do logu
PrintWriter printIntoLog = new PrintWriter(log);
while (true) {
//podanie sciezki szukanego pliku
System.out.println("Input file's directory you are looking for: ");
String path = input.nextLine();
//utworzenie obiektu do danego pliku
File searchedFile = new File(path);
//sprawdzenie czy plik istnieje- jesli tak to zapisuje do logu jego sciezke i usuwa go
try{
if (searchedFile.exists()) {
printIntoLog.println(searchedFile.getPath());
//searchedFile.delete();
}else{
throw new MyFileNotFoundException("Searching stopped for 1 minute.");
}
}catch(MyFileNotFoundException ex){
System.out.println(ex);
TimeUnit.MINUTES.sleep(1);
}
}
}
}
You should close the PrintWriter reference before finishing execution. It's an enforced practice to close a file after read/write on it.
If you are using Java +7 you can use the fancy way withtry-with-resources syntax
```java
try (PrintWriter printIntoLog = new PrintWriter(log)) {
while (true) {
....
}
}
```
With older versions you can use try-finally syntax
try {
while(true) {
...
}
} finally {
printIntoLog.close();
}
See
Java – Try with Resources
I'm having problems with my try-catch exception here. Actually what it does is to prompt the user for the name of a text file say, Robot.txt but if say the file does not exist, I have to make sure that the application reprompts the user for the file name. Hope you guys can understand I'm still a newbie here so please feel free to provide suggestions or advices on my coding etc. Cheers!
Main method class:
import java.io.*;
import java.util.Scanner;
import java.util.Vector;
class TestVector3 {
public static void main(String [] args)
{
System.out.println("Please enter the name of the text file to read: ");
Scanner userInput = new Scanner(System.in);
Vector <KillerRobot> robotDetails = new Vector <KillerRobot>();
KillerRobot robot;
Scanner fileInput = null;
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :"); //Reprompt user for name of the text file
fileInput = new Scanner(userInput.nextLine());
}
while(fileInput.hasNext())
{
robot = new KillerRobot();
String first = fileInput.next();
robot.setName(first);
String second = fileInput.next();
robot.setMainWeapon(second);
int third = fileInput.nextInt();
robot.setNumberOfKills(third);
robotDetails.add(robot);
}
for(KillerRobot i : robotDetails)
{
System.out.println(i);
}
fileInput.close();
}
}
KillerRobot class file:
class KillerRobot {
private String name;
private String mainWeapon;
private int numberOfKills;
KillerRobot()
{
}
public String getName()
{
return name;
}
public String getMainWeapon()
{
return mainWeapon;
}
public int getNumberOfKills()
{
return numberOfKills;
}
public String toString()
{
return name + " used a " + mainWeapon + " to destroy " + numberOfKills + " enemies ";
}
public void setName(String a)
{
name = a;
}
public void setMainWeapon(String b)
{
mainWeapon = b;
}
public void setNumberOfKills(int c)
{
numberOfKills = c;
}
}
As you state that you are a beginner, let us first look at the relevant part of your code, to make sure that we talk about the same thing:
Scanner fileInput = null;
try {
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
You have an input and you want to check this input for a condition and require a new input until this condition is fulfilled. This problem can be solved using a loop like the following:
Scanner fileInput = null;
do {
System.out.println("Enter file name :");
try {
fileInput = new Scanner(new File(userInput.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
}
} while(fileInput == null);
So finally, why does this work? The fileInput variable is set to null and will remain null until the given file is successfully read from standard input because an exception is thrown otherwise what prevents the fileInput variable to be set. This procedure can be repeated endlessly.
On a side note, for performance reasons, it is normally not a good idea to implement control flow that is based on exceptions. It would be better to check for a condition if a file exists via File::exists. However, if you read the file after checking for its existence, it might have been deleted in the meantime which introduces a racing condition.
Answer to your comment: In Java (or almost any programming language), you can inline expressions. This means that instead of calling two methods in two different statements as in
Foo foo = method1();
Bar bar = method2(foo);
you can simply call
Bar bar = method2(method1());
This way, you save yourself some space (what becomes more and more important if your code gets longer) as you do not need the value that you saved in foo at any other place in your code. Similarly, you can inline (which is how this pattern is called) from
File file = new File(userInput.nextLine())
fileInput = new Scanner(file);
into
fileInput = new Scanner(new File(userInput.nextLine()));
as the file variable is only read when creating the Scanner.
Try putting the try-catch in a loop like below:
Scanner fileInput = null;
while (fileInput==null)
{
try
{
System.out.println("Please enter the file name.");
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
}
}
Next you could think of moving the File creation part into separate method, so that the code was cleaner.
Do not fall for try-catch instead add this as your functionality. Exceptions are naturally for run time error handling not for logic building.
Check if file exists at given location.
File textFile = new File(userInput.nextLine());
// Check if file is present and is not a directory
if(!textFile.exists() || textFile.isDirectory()) {
System.out.println("Error - file not found!");
//Reprompt user for name of the text file
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
You can put while loop instead of if loop if you want to continuously prompt user until correct path is entered.
You can call back your main(), like following
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
main(args); // recursively call main() method
}
Now if user first attempt wrong then your code will asked to re enter file name.
How to check isFile exist?
File file = new File(filePathString);
if(file.exists() && !file.isDirectory()){
System.out.println("file exist");
}
This really is an XY problem because you assumed the only way to check for a file existence is by catching a FileNotFoundException (hence asking about try-catch exception handling) whereas other means exist to help you avoid a try-catch idiom in an elegant manner.
To check if a file exists at the given path or not you can simply use the File.exists method. Please also see the File.isFile method and/or the File.isDirectory method to verify the nature of the targeted File object.
EDIT : As stated by raphw, this solution is best used in simple scenario since it can incur a race condition in the case of concurrent file deletion happening during the file existence check. See his answer for handling more complex scenario.
Currently trying to write a program to take input from a file and store it in an array. However, whenever I try to run the program the file cannot be found (despite file.exists() and file.canRead() returning true).
Here is my code:
public void getData (String fileName) throws FileNotFoundException
{
File file = new File (fileName);
System.out.println(file.exists());
System.out.println(file.canRead());
System.out.println(file.getPath());
Scanner fileScanner = new Scanner (new FileReader (file));
int entryCount = 0; // Store number of entries in file
// Count number of entries in file
while (fileScanner.nextLine() != null)
{
entryCount++;
}
dirArray = new Entry[entryCount]; //Create array large enough for entries
System.out.println(entryCount);
}
public static void main(String[] args)
{
ArrayDirectory testDirectory = new ArrayDirectory();
try
{
testDirectory.getData("c://example.txt");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
(In it's current state the method is only designed to count the number of lines and create the array)
The console output is as follows: true true c:/example.txt
The program seems to throw a 'FileNotFoundException' on the line where the scanner is instantiated.
One thing I have noticed when checking the 'file' object when debugging is although it's 'path' variable has the value "c:\example.txt", it's 'filePath' value is null. Not sure if this is relevant to the issue or not
EDIT: After Brendan Long's answer I have updated the 'catch' block. The stack trace reads as follows:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at assignment2.ArrayDirectory.getData(ArrayDirectory.java:138)
at assignment2.ArrayDirectory.main(ArrayDirectory.java:193)
Seemingly the scanner doesn't recognize the file and thus can't find the line
This code probably doesn't do what you want:
try
{
testDirectory.getData("c://example.txt");
}
catch (Exception ex)
{
new FileNotFoundException("File not found");
}
If you catch any exception, you run the constructor for a FileNotFoundException and then throw it away. Try doing this:
try
{
testDirectory.getData("c://example.txt");
}
catch (Exception ex)
{
ex.printStackTrace();
}
According to the javadoc for Scanner, nextLine() throws this exception when there is no more input. Your program seems to expect it to return null, but that's now how it works (unlike, say, BufferedReader which does return null at the end of the input). Use hasNextLine to make sure there's another line before using nextLine.
I think it's easier to just show the code and the output I'm getting than trying to explain it :)
This is from my main method:
//prompt user for filename
System.out.println("Please enter the text file name. (Example: file.txt):");
String filename = ""; //will be used to hold filename
//loop until user enters valid file name
valid = false;
while(!valid)
{
filename = in.next();
try
{
reader.checkIfValid(filename);
valid = true; //file exists and contains text
}
catch (Exception e)
{
System.out.println(e + "\nPlease try again.");
}
}
And this is the reader.checkIfValid method:
public void checkIfValid(String filename) throws InvalidFileException, FileNotFoundException
{
try
{
in = new Scanner(new File(filename));
if (!in.hasNextLine()) // can't read first line
throw new InvalidFileException("File contains no readable text.");
}
finally
{
in.close();
}
}
This is the output I get when a nonexistent file is entered:
Please enter the text file name. (Example: file.txt):
doesNotExist.txt
java.lang.NullPointerException
Please try again.
Why is the System.out.println(e) getting a NullPointerException? When I enter an empty file or a file with text, it works just fine. The empty file prints the InvalidFileException (a custom exception) message.
When I put a try-catch statement around the "in = new Scanner(new File(filename));", and have the catch block display the exception, I do get the FileNotFoundException printed out, followed by the NullPointerException (I'm not entirely sure why the catch block in the main method would be activated if the exception was already caught in the checkIfValid method...).
I've spent a while on this and I'm completely clueless as to what's wrong. Any help would be appreciated. Thanks!
edited: I think the null pointer comes from the call to reader, it is poor practise to catch all exceptions as you no longer know where they came from!
Maybe the checkIfValid method should just check if the filename is valid?
public boolean checkIfValid(String filename) {
try {
File file = new File(filename);
return file.exists();
} catch (FileNotFoundException) {
System.out.println("Invalid filename ["+filename+"] "+e);
}
}
Then the code calling it could look like;
filename = in.next();
valid = reader.checkIfValid(filename);
if (valid)
List<String> fileContents = readFromFile(filename);
Then contain all the file reading logic in it's own method like this;
public List<String> readFromFile(filename) {
List<String> fileContents = new ArrayList<String>();
try {
in = new Scanner(new File(filename));
while (in.hasNextLine()) {
fileContents.add(in.nextLine);
}
} catch (IOException e){
//do something with the exception
} finally {
in.close();
}
return fileContents;
}
My mistake was something only I could've seen. I was catching all the exceptions so I wasn't able to see where it was coming from. Thank you for helping!
I need to save some data into text file. I'm using class Files with its method write().
If such file doesn't exist - everything alright. The problem is if such file already exists it appends new data to the end of the file. And I need to clear it first. The code is:
public static void main(String[] args) {
DepoList test0 = new DepoList();
test0.init();
ArrayList<Depo> list0 = test0.getList();
Collections.sort(list0);
for (Depo depo : list0) {
String str = String.format("sum = %1$8.2f interest = %2$7.2f\n", depo.getSum(), depo.getIncome());
System.out.format(str);
try {
Files.write(Paths.get("depo.txt"), str.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println();
I think I need to add some another StandardOpenOperation. How to clear the file before putting data there?
Remove StandardOpenOption.CREATE,Standardoption.APPEND this just appends your new data to the existing one
Use Files.write((Paths.get("depo.txt"), str.getBytes());