I have a simple text file and for some reason, it cannot be found. I don't see anything wrong with the code because I got it from a site, and I am starting to think that I didn't place the text file in the right place. Any suggestion please?
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MainFavorites {
public static void main(String[] args) throws IOException {
/**
* finds pathway to the file
*/
// File file = new File("icecreamTopping.txt");
// System.out.println(file.getCanonicalPath());
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("icecreamTopping.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
//System.out.println(sCurrentLine);
myFileLines.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
int numElements = myFileLines.size();
System.out.println ("there are n lines in the file:" + numElements);
for (int counter = numElements-1; counter >= 0; counter--) {
String mylineout = myFileLines.get(counter);
System.out.println (mylineout);
}
}
}
File content:
1- Blueberry
2- Banana Buzz
3- Cookie Batter
My stack trace is this:
java.io.FileNotFoundException: C:\Users\homar_000\workspace\RankFavorites\icecreamTopping.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at MainFavorites.main(MainFavorites.java:28)
Replace below line
reader = new BufferedReader(new FileReader("icecreamTopping.txt"));
with
reader = new BufferedReader(new FileReader("resources/icecreamTopping.txt"));
and put the file under resources folder that resides parallel to src folder.
Sample code:
Reading a file abc.txt from resources folder
reader = new BufferedReader(new FileReader("resources/abc.txt"));
Here is the project structure
Try below code to find out where it is pointing to file icecreamTopping.txt.
File f=new File("icecreamTopping.txt");
System.out.println(f.getAbsolutePath());
After getting the absolute path, just place the file there.
--EDIT--
As per your last comments, put icecreamTopping.txt file in the project RankFavorites directly as shown in below snapshot and It will definitely solve your problem.
Found out what was the problem. It was unnecessary for me to put the file extension so I removed the .txt because when I kept it, it read it as "icecreamTopping.txt.txt"
Move the text file to java/main/resources folder if you are using Maven or to classes folder, so that it will be in classpath. Then use the following line of code to get the file path. Replace MyClass with your class name. Use the path as argument in FileReader.
String path = MyClass.class.getClassLoader().getResource("text_file.txt").getPath();
BufferedReader reader = new BufferedReader(new FileReader(path));
Try to use File class to detect your file in storage:
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
JSONParser parser = new JSONParser();
ObjectMapper mapper = new ObjectMapper();
try {
Object obj = parser.parse(new FileReader("/home/sahan/Desktop/data.json"));
ObjectNode objNode = mapper.convertValue(obj, ObjectNode.class);
System.out.println(objNode);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
I have the following code which attempts to run and print a specified error message when the file is not found. However, it's running perfectly without giving output about the error that happens. the text file name does not exist in my directory. Can anyone shed some light on this?
When I run this it runs perfectly without any error (not sure if that's a good thing).
import java.io.*;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.IOException;
public class filereader {
public static void main (String[] args) {
String fileName = "nonExistenceFileName.csv";
File textFile = new File(fileName);
try (BufferedWriter br = new BufferedWriter(new FileWriter(textFile))) {
String line;
Scanner input = new Scanner(textFile);
while(input.hasNextLine()) {
line = input.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("Can't find file " + textFile.toString());
} catch (IOException e) {
System.out.println("Unable to read file");
}
When you try to create a BufferWriter object on a non-existing file
BufferedWriter br = new BufferedWriter(new FileWriter(textFile));
it creates a new file (if not already exists)
So no exception is thrown since the file is already present
you should check if the file exist before, otherwise, BufferWriter creates one if it doesn't exist. use
if (textFile.exists()){
//what to do if file exist
}else{
//Throw FileNotFound Error
}
Write a program that reads in a file and displays its contents. Get the input filename from the command line. For example, if your program is in the file Display.class, you would enter on the command line:
java Display t1.txt
to display the content file t1.txt.
How can this be done?
you can use FileReader or BufferedReader to read the contents of file. below code may be helpful to you
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Display {
public static void main(String[] args) {
if(args.length > 0) {
String fileName = args[0];
try {
File file = new File(fileName);
if(file.exists() && file.isFile() ) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
System.out.println("FileContents are...");
while((line = br.readLine()) != null) {
System.out.println(line);
}
}else{
System.out.println("File Not Found");
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I can't figure out for the life of me what is wrong with this program:
import java.io.*;
public class EncyptionAssignment
{
public static void main (String[] args) throws IOException
{
String line;
BufferedReader in;
in = new BufferedReader(new FileReader("notepad encypt.me.txt"));
line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
System.out.println(line);
}
}
The error message says that the file can't be found, but I know that the file already exists. Do I need to save the file in a special folder?
The error is "notepad encypt.me.txt".
Since your file is named "encypt.me.txt", you can't put a "notepad" in front of its name. Moreover, the file named "notepad encypt.me.txt" probably didn't exist or is not the one that you want to open.
Additionally, you have to provide the path ( absolute or relative ) of your file if it's not located in your project folder.
I will take the hypothesis that your are on a Microsoft Windows system.
If your file has as absolute path of "C:\foo\bar\encypt.me.txt", you will have to pass it as "C:\\foo\\bar\\encypt.me.txt" or as "C:"+File.separatorChar+"foo"+File.separatorChar+"bar"+File.separatorChar+encypt.me.txt".
If it's still not working, you should verify that the file :
1) Exist at the path provided.
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.exists());
If the path provided is the right one, it should be at true.
2) Can be read by the application
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.canRead());
If you have the permission to read the file, it should be at true.
More informations:
Javadoc of File
Informations about Path in computing
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Reference: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
I asked a similar question before regarding I/O using Java.
I'm trying to copy a list of strings into another file.
package file;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
FileWrite fW = new FileWrite();
try (BufferedReader br = new BufferedReader(new FileReader("B:\\inLarge.dat")))
{
String stCurrent;
while ((stCurrent = br.readLine()) != null) {
System.out.println(stCurrent);
fW.serializeAddress(stCurrent, stCurrent);
}
} catch (IOException e) {
e.printStackTrace();
}
//fW.serializeAddress("Boston", "Canada");
}
}
And
package file;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.io.IOException;
public class FileWrite {
public void serializeAddress(String city, String country){
try
{
File file = new File("B:\\outLarge.txt");
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(city + " " + country);
bw.close();
System.out.println("Done");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
But the ending output file has only one result, how do I make it copy everything?
I am thinking buffered-writer somehow needs to be in the loop to write new ones on top of existing ones? But not sure how to implement that.
Thanks a lot.
You are overwriting the file contents every time you call your serialize method, because you didn't open the file in append mode. To prevent overwriting, open the file in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
However, this is one case where the solution is probably over-engineered. For efficiency you really should be opening your file just once. Here's an example:
public static void main(final String[] args) {
try {
final BufferedReader reader = new BufferedReader(new FileReader("infile.txt"));
final PrintWriter writer = new PrintWriter(new File("outfile.txt"));
String inputLine;
while((inputLine = reader.readLine()) != null) {
writer.println(inputLine);
}
reader.close();
writer.close();
} catch(final Exception e) {
e.printStackTrace();
}
}
You're overwriting the existing file every time you open it. Instead append to it.
Change
FileWriter fw = new FileWriter(file.getAbsoluteFile());
to
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
I was trying an exercise of deleting lines from a file not starting with a particular string.
The idea was to copy the desired lines to a temp file, delete the original file and rename the temp file to original file.
My question is I am unable to rename a file!
tempFile.renameTo(new File(file))
or
tempFile.renameTo(inputFile)
do not work.
Can anyone tell me what is going wrong? Here is the code:
/**
* The intention is to have a method which would delete (or create
* a new file) by deleting lines starting with a particular string. *
*/
package com.dr.sort;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RemoveLinesFromFile {
public void removeLinesStartsWith(String file, String startsWith, Boolean keepOrigFile) {
String line = null;
BufferedReader rd = null;
PrintWriter wt = null;
File tempFile = null;
try {
// Open input file
File inputFile = new File(file);
if (!inputFile.isFile()) {
System.out.println("ERROR: " + file + " is not a valid file.");
return;
}
// Create temporary file
tempFile = new File(file + "_OUTPUT");
//Read input file and Write to tempFile
rd = new BufferedReader(new FileReader(inputFile));
wt = new PrintWriter(new FileWriter(tempFile));
while ((line = rd.readLine()) != null) {
if (line.substring(0, startsWith.length()).equals(startsWith)) {
wt.println(line);
wt.flush();
}
}
rd.close();
if (!keepOrigFile) {
inputFile.delete();
if (tempFile.renameTo(new File(file))) {
System.out.println("OK");
} else {
System.out.println("NOT OK");
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
finally {
if (tempFile != null && tempFile.isFile()) {
wt.close();
}
}
}
}
I guess you need to close your PrintWriter before renaming.
if (line.substring(0, startsWith.length()).equals(startsWith))
should instead be the opposite, because we don't want the lines that are specified to be included.
so:
if (!line.substring(0, startsWith.length()).equals(startsWith))