I have to read a text and I created a method
public void load(String fname){
try{
BufferedReader reader = new BufferedReader(new FileReader(fname));
String id_cliente = reader.readLine();
while(id_cliente!=null){
String name_surname = reader.readLine();
int num_titoli = Integer.parseInt(reader.readLine());
String[] sb = name_surname.split(" ");
Cliente cl = new Cliente(id_cliente,sb[0],sb[1]);
clientilist.put(Integer.parseInt(id_cliente.substring(1)),cl);
for(int i = 0; i < num_titoli; i++){
cl.addTitolo(String titolo = reader.readLine());
}
id_cliente = reader.readLine();
}
}
catch(FileNotFoundException fnfe){
try{
}
catch(FileNotFoundExeption fnfe){
System.exit(0);
}
}
catch(IOException ioe){
}
}
what I would do is to check if the fname file exists.if it's not a FileNotFoundExceptionwill be thrown.Inside it I have to try to open another file.if it is not present so exit with an error message.how can i do?
In the catch block of the first try catch statement you could put any code you want and it will be executed when the exception occurs. You could read another file, try reading the same file again, ask user to point to the correct file, ...
But as mentioned a better solution is to check if the file exists before you create the reader. And if that fails you can fallback on another file (what if that one fails also?)
In the next code I adapted your method to have a check and throw an exception if file isn't valid. On using that method you can react on that. Note that you haven't opened any readers if you gave 2 invalid filenames.
try{
load(fname);
}catch(Exception e){
try{
load(alternativeFName);
}catch(Exception e){
System.out.println("None of the files are available");
e.printStackTrace();
}
}
And this is how your load function would look like:
public void load(String fname) throws Exception {
// try opening file
File file = new File(fname);
// check if valid file
if( !file.exists() ){
// if no valid file throw exception so we can react on that
throw new Exception("File not available: "+fname);
}
//your code for reading here, at this point you know the file exists
//...
}
It´d be simpler to check first if the file exist, instead of waiting for the exception:
File f = new File(fname);
if (!f.exists()) {
// similarly, check for the existence of the other file, exit if necessary
}
Related
Im having a problem in checking if a file exists in Java. However the IF block seems to work , but the ELSE seems dont. see, when a file exist, it will prompt a box that says, 'File found.' which happens in my program whenever a file do exist, the problem is errors flood in my console when a file dont exist. Can somebody tell me what's the easier and shorter way of coding my problem? thanks ! here's my code
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
File f = new File(textField.getText());
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
{
JOptionPane.showMessageDialog(null, textField.getText()+" found" );
while ((sCurrentLine = br.readLine()) != null) {
textArea.append(sCurrentLine);
textArea.append(System.lineSeparator());
}
}
else
{
JOptionPane.showMessageDialog(null, textField.getText()+" not found" );
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
The problem is with this line:
br = new BufferedReader(new FileReader(path+f));
You're appending a File to a String, which doesn't make sense. You should append a String to a String, in this case textField.getText()) appended to path.
This line will throw an exception if the file doesn't exist as per the documentation of FileReader:
Throws:
FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
This causes your program to reach the catch clause and print an exception stack trace. You should only call this line when f.exists() returns true:
if (f.exists())
{
br = new BufferedReader(new FileReader(path + textField.getText()));
...
}
Look at these lines of your code:
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
You are trying to open the file before checking whether it exists. So if the attempt to open it fails with a FileNotFoundException, the test is never reached.
String path = "C:\\Path\\To\File\\Directory\\";
String fileName = "NameOfFile.ext";
File f = new File(path, fileName);
if(f.exists()) {
//<code for file existing>
} else {
//<code for file not existing>
}
You have to instantiate the BufferedReader after checking the existence of the file.
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
File f = new File(path + textField.getText());
...
if (f.exists())
{
br = new BufferedReader(new FileReader(f.getAbsolutePath())); // or br = new BufferedReader(f);
...
I want to extract the first column in a file using the delimiter "," and save it into a new File.
Output generates this exception :
Exception in thread "main" java.lang.NullPointerException
at Extract.main(Extract.java:26)
Here is the code that I used butI am not sure if it is correct or not:
public class Extract {
public Extract(){
}
public static void main(String[] args) {
BufferedReader in = null;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/home/omar/Téléchargements/nursery.tmp"));
in = new BufferedReader(new FileReader("pima.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
if (splited.length > 0)
{
out.append(splited[0].toString());
out.newLine();
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
File f = new File("prima.txt");
f.delete();
File f2 = new File("pima.tmp");
f2.renameTo(new File("pima.txt"));
}
}
Remove the first line, ie read = in.readLine();, from inside your while() loop.
The problem is that you are reading the line when you are checking the while condition and inside while loop you are reading a line again (but this time a new line, because readLine not only reads a line but also moves the reading pointer to next line) so you are getting the next line.
Once you are past the end of the file you get null instead of a line, that is why you are getting Exception.
static boolean exists(String location) {
File path = new File(location);
if (path.exists()){
return true;
}
else {
return false;
}
}
static boolean checkFile(String location1) throws IOException {
if ( exists(location1) ) {
File file = new File(location1);
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek( raf.length()-1 );
byte lastByte = raf.readByte();
raf.close();
if (lastByte == 2) {
return true;
}
else {
return false;
}
}
else {
System.out.println("File does not exist, please try again: ");
Scanner sk = new Scanner(System.in);
String newLocation = sk.nextLine();
checkFile(newLocation);
sk.close();
return false;
With that said, I have checked with a separate method whether a file even exists, however, I would like to now compress the above into a single method by somehow recursively utilizing the try-catch:
static boolean checkFile(String location) {
try {
File file = new File(location);
}
catch (FileNotFoundException e) {
System.out.println("File does not exist, please try again: ");
Scanner sk = new Scanner(System.in);
String newLocation = sk.nextLine();
checkFile(newLocation);
}
//the following if-sentence checking whether some byte checks up.
}
1st problem: how can I create a new random access file using the File file inside try? I did try initializing it before try File file = null; , but then it throws NullPointer, because after it catches the exception, the method is called again and the file will automatically be null.
Another idea was to try-catch inside a do-while-loop , but then I was thinking about do while what? I would have to check whether the file exists, considering that's what I'm already doing with try-catch it becomes redundant.
What can I do to try-catch as long as I input a path that is not a file and then proceed with the if sentence all in one method?
If you have to use try/catch, which I really don't recommend, you could do it in a "forever" loop, something like this.
public static FileReader readerForPromptedFile() {
Scanner keyboard = new Scanner(System.in);
while (true) {
try {
System.out.println("Please enter a file name");
String fileName = keyboard.nextLine();
return new FileReader(fileName);
} catch (FileNotFoundException e) {
System.out.println("File not found, please try again");
}
}
}
Something like this should work:
static boolean checkFile(String location) {
while (!exists(location)){
System.out.println("File does not exist, please try again: ");
Scanner sk = new Scanner(System.in);
String newLocation = sk.nextLine();
}
try {
//the following if-sentence checking whether some byte checks up.
}
catch (IOException e) {
// Handle exception
}
}
It's generally frowned on to use a method which could throw an exception if there is a reasonable way to check whether it should work first - in that case the behaviour isn't really an exception, it's more of a precondition. It also adds quite a large performance overhead.
I'm trying to read a moderately sized txt file (65,00 words) into a String, then a string array. The bufferedreader throws the "could not read file" catch. When I clear it, a small part of the contents of the text file is shown in the system.out. I do not get the error with smaller text files. I'm a beginner and I'm having a lot of trouble trying to narrow down the issue.
Why isn't the BufferedReader ingesting the entire file? And why is the "could not read file" error being thrown?
public class Main {
public static void main(String[] args) {
final Guid Main = new Guid(); //creates instance of Guid
Main.mergeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
merge();
}
});
}
static void merge()
{
//read file and turn into string
String pathone = open(Guid.PathOne);
System.out.print(pathone);
//parse and format
//String[] oneArray = pathone.replace("\n"," ").split(" ");
//get pathtwo text
//String pathtwo = open(Guid.PathTwo);
//parse and format
//load into array
//compare array entries
//add new array entry
//sort array
//write array to paththree file
//for(int i=0; i<oneArray.length;i++)
//{
//System.out.println(oneArray[i]);
//}
}
public static String open(JTextArea Path)
{
String record = null;
FileReader frFile = null;
try {
frFile = new FileReader(Path.getText());//gets file from Path
BufferedReader brFile = new BufferedReader(frFile);//creates buffered reader
record = brFile.readLine() + "\n"; //gets contents of file and puts it into a string
brFile.mark(0);
while (brFile.read() != -1) //loop to read the rest of the text file
{
brFile.reset();
record = record + brFile.readLine() + "\n";
brFile.mark(0);
}
}
catch (FileNotFoundException e) //catch path is in error
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not find file.");
}
catch (IOException e) //catch if file cannot be read
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not read file.");
}
try { //closes file
frFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return record;
}
}
Do in this way. Remove reset() and mark() methods if you want to read the entire file.
StringBuilder record = new StringBuilder();
BufferedReader brFile = new BufferedReader(frFile);
String line = null;
while ((line = brFile.readLine()) != null) {
record.append(line).append("\n");
}
Note:
Don't forget to close the stream.
Use finally block to close the stream
Use StringBuilder or StringBuffer to append the string.
Use System.getProperty("line.separator") to get the system specific line separator
Have a look at Java7 try-with-resources Statement advantage
readLine will read the first line of your document.
Try with it (not tested):
String lineReaded;
while ((lineReaded=brFile.readLine())!=null)
{
record +=linereaded+"\n";
}
Niko
You might like to use Files.readAllLines
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I've been trying to rename files and folders in a given folder by finding and replacing a substring in their name. Also, the name of file is contained in their contents also. I need to replace it to the new name.
For Example:
Change "XXX" to "KKK" in all the files and folder names and also in file contents:
Original file name: 0001_XXX_YYY_ZZZ.txt
New file name: 0001_KKK_YYY_ZZZ.txt
Following is the code that I'm using.
When I run the following code without calling the function replaceText(), its renaming the file and folder. But, when I try to change the text of file and then rename the file and folder; contents of file is changed but renaming of both file and folder fails.
Please help.
public class FindReplaceAnywhere {
public static void main(String[] args) {
String find = "XXX";
String replace = "KKK";
String baseLoc = "D:\\0001_XXX_YYY_ZZZ";
FindReplaceAnywhere obj = new FindReplaceAnywhere();
File baseLocObj = new File(baseLoc);
LinkedList<File> baseFolderList = new LinkedList<File>();
// Add base folder object to list
baseFolderList.add(baseLocObj);
// Get list of files in the folder
for(File file: baseLocObj.listFiles()) {
baseFolderList.add(file);
}
// Rename the files, folders & contents of files
obj.rename(baseFolderList, find, replace);
}
public void rename(LinkedList<File> fileList, String find, String replace) {
String tempStr = null;
int beginIndex = 0;
int endIndex = 0;
File tempFile;
System.out.println(">>> Batch Rename Process Begins >>>\n");
for(File aFile:fileList) {
// If Object is File, change the text also
if(aFile.isFile()) {
replaceText(aFile,find,replace);
}
}
for(File aFile: fileList) {
System.out.println("Processing>>>");
System.out.println(aFile.getPath());
if(aFile.getName().contains(find)) {
// Get the name of File object
beginIndex = aFile.getPath().length() - aFile.getName().length();
endIndex = aFile.getPath().length();
tempStr = aFile.getPath().substring(beginIndex, endIndex);
tempStr = tempStr.replace(find, replace);
}
else {
System.out.println("Error: Pattern not found\n");
continue;
}
tempFile = new File(aFile.getParentFile(),tempStr);
boolean success = aFile.renameTo(tempFile);
if(success) {
System.out.println("File Renamed To: "+tempFile.getName());
}
else {
System.out.println("Error: Rename Failed\nPossible Cause: File is open in another application");
}
System.out.println("");
}
}
/**
* Replace the text of file if it contains filename
*/
public void replaceText(File file, String find, String replace) {
String fullText = "";
String line = "";
String fileName = "";
String replaceName = "";
BufferedReader in;
BufferedWriter out;
// Read the file contents
try {
in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null) {
fullText+=line+"\n";
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
// Replace the text of file
fileName = file.getName().substring(0, file.getName().indexOf("."));
replaceName = fileName.replace(find, replace);
fullText = fullText.replace(fileName, replaceName);
// Write the replaced text to file
try {
out = new BufferedWriter(new FileWriter(file));
out.write(fullText);
out.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
It doesn't look like you're closing your input (in) file after reading it, which will hold that file open - Under *nix a rename should still work, but it will fail under Windows:
Use a finally block to ensure that the resource is closed.. but only after you're assured that it was opened.
While I'm at it, please allow me to suggest another change to the code:
Move "declarations" to the the absolute last point in the code where they can be made.. avoid declaring early. In this case, both in and out are unnecessarily declared early. There are others; I'll leave that for you to work out.
So, for the input file:
// Read the file contents
try {
BufferedReader in = new BufferedReader(new FileReader(file));
// If you got this far, the file is open...
// use try/finally to ensure closure.
try {
while((line = in.readLine()) != null) {
fullText+=line+"\n";
}
}
finally {
in.close();
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
and for the output file:
// Write the replaced text to file
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
try {
out.write(fullText);
}
finally {
out.close();
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}