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
Related
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.
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.
I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.
What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.
Here is the code:
import java.io.*;
import java.util.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
}
The data file should be a simple display of numbers 1 through 9.
Thanks for your input.
On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.
Solution: Use a different location
DataOutputStream out =
new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));
Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work
You should have a look at the exception itself:
System.out.println("No file exist");
System.out.println(ex.getMessage());
Perhaps you have not the necessary rights, to access C:\ with your program.
To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.
public static void main(String[] args) throws IOException {
File output = new File("data.txt");
if(!output.exists()) output.createNewFile();
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
I'm trying to make a save function for a program I'm working on, and for some reason whenever I run it, it only gets past the first line of the try{} statement.
My code is as appears below.
public void saveGame() {
System.out.println("saveGame");
try
{
System.out.println("try saveGame");
BufferedWriter b = new BufferedWriter(new FileWriter("chardata.txt"));
System.out.println("try saveGame2");
String sp = System.getProperty("line.separator");
System.out.println("try saveGame3");
b.write("Miscellaneous char data here");
b.close();
}
catch(IOException ex)
{
System.out.println("File Writing Error");
}
}
When I run the program, the only lines that get printed are "saveGame" and "try saveGame." There is no "File Writing Error" either, it simply doesn't do anything after the "try saveGame" line. I'm not sure if this is relevant, but I am doing this from a computer at a school, which may have restricted permissions. Any kind of explanation and/or help would be much appreciated.
I think a better way to write your file would be using FileOutputStream and OutputStreamWriter.
Additionaly, you should move your b.close to a finally statement because if an exception is thrown before that b.close was executed, it never will be executed.
public void saveGame() {
System.out.println("saveGame");
try
{
System.out.println("try saveGame");
String path = "./chardata.txt"; //your file path
File file = new File(path);
FileOutputStream fsal = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fsal);
Writer w = new BufferedWriter(osw);
System.out.println("try saveGame2");
String sp = System.getProperty("line.separator");
System.out.println("try saveGame3");
w.write("Miscellaneous char data here");
}
catch(IOException ex)
{
System.out.println("File Writing Error");
}
finally{
if(w!=null)
w.close();
}
}
I have a method called readinFile and if the user enters a wrong file instead of exiting I wanted to call the method readinFile again inside the readinFile method I ask the user for new filename. The problem I am running into is the first time it goes through it and gives the exception file not found than it goes through the catch(). I want it to call the method and not run the last inputStream.
try
{
inputStream = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException E)
{
readinfile(table, numberOfColumns, header,
original, sntypes,displaySize,
writeOut,inputStream,fileName );
System.out.print("It got here after doing the method call");
}
You should generally not use exceptions for branching. Just check for the existance of the file using File.exists, like so:
new File(fileName).exists()
You probably want to do something like this:
String fileName;
do {
System.out.println("Please enter filename");
fileName = getFileNameFromInput();
File file = new File(fileName);
} while (!file.exists());
readFile(file);
EDIT:
As Bruno Reis has pointed out, this will only check if the file exists when the user specified the file name. If the file was to be moved/deleted between specifying the file name and reading it then a FileNotFoundException would still be thrown.
To reduce the risk of this you can lock the file as discussed in this question.
bool invalidFilename = true;
string fileName;
while(invalidFilename)
{
readinfile(...);
invalidFilename = !new File(fileName).exists();
}
inputStream = new Scanner(new FileInputStream(fileName));
You can check if the filename the user input does exists or not, and don't need to catch the exception. (which is not a good design code, decrease the readability of the code)....
as inflagranti said,
you can do this pseudocode
if (!new File(filename).exists()){
//read your other file from user
readinfile(....)
}
To get what you are after, without the chance of the file being deleted after you check for it existing but before you open it do something like:
boolean done = false;
String fileName = fileNameParameter;
while(!done)
{
try
{
inputStream = new Scanner(new FileInputStream(fileName));
done = true;
}
catch(FileNotFoundException E)
{
fileName = /* ask the user for the file name */
}
}