Reading in Data (Java) - java

I am having trouble loading data into my Java program. The program says the file exists, but FileReader is giving a FileNotFoundException. I have tried the full path and made sure all files are closed. I am using the Eclipse IDE. Any suggestions?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class ReadCSV {
public static void main(String[] args) {
String filepath = "/Users/mrodgers/Documents/other/languages/java/eclipse/ReadCSV/src/data.csv";
//String filepath = "~/Desktop/data.csv";
//String filepath = "data.csv";
File mjr = new File(filepath);
System.out.println(mjr.exists());
FileReader fr = new FileReader(mjr);
// BufferedReader br = new BufferedReader(fr);
}
}

This works on my machine, with the filename set to one that I have of course.
But I did have to wrap the creation of FileReader in a try/catch for FileNotFound exception -- is that what you mean? The compiler tells you that you must catch FileNotFound if you use that FileReader constructor?
Unless/until you do that, eclipse should (and does, on my machine) mark the call to the FileReader constructor as an error because that exception is not caught.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FilePlay
{
public static void main(String[] args) {
String filepath = "/Users/ralph/Documents/My Chess Database/r-b.pgn";
//String filepath = "~/Desktop/data.csv";
//String filepath = "data.csv";
File mjr = new File(filepath);
System.out.println(mjr.exists());
try
{
FileReader fr = new FileReader(mjr);
BufferedReader br = new BufferedReader(fr);
}
catch (FileNotFoundException fnf)
{
fnf.printStackTrace();
}
}
}

Related

BufferedReader and FileReader not working in

I'm just trying to read text from an existing file.txt But this program shows 2 errors
for the FileReader(file)) it says : Expected 0 arguments but found 1
and for reader.readLine() it says : Cannot resolve method 'readLine' in 'BufferedReader'
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReader {
public static void main(String[] args) {
File file = new File("fileExample.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (IOException e) {
e.printStackTrace();
}
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
Rename your class to something other than BufferedReader, and import the right class from the JDK:
import java.io.BufferedReader;
Otherwise the compiler will look for a constructor of your own class.
Note about exception handling: given the code you have, if an IOException occurs when creating the BufferedReader, then the subsequent code will throw a NullPointerException. It may be better to just wrap the entire code in a try-with-resources block, or have the main method throws IOException.

Why i am no getting able to write text into a file

I have written a simple code to write text into file but i am not able to figure out why text is not written to file. I have written a class with method which will take text file as input and create the text file if it is not exist
here is the code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class OutputFile {
public static BufferedWriter fbw = null;
public BufferedWriter createFile(String text)
{
try{
File file =new File(text);
if(!file.exists()){
file.createNewFile();
}
FileWriter writer = new FileWriter(text,true);
fbw =new BufferedWriter(writer);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
return fbw;
}
public static void main(String args[]) throws IOException
{
String resultFilePath = "C:/Users/Desktop/stringcompare/output.txt";
OutputFile file = new OutputFile();
fbw = file.createFile(resultFilePath);
fbw.write("hello");
fbw.newLine();
fbw.close();
}
}
Try this:
try(BufferedWriter bw = new BufferedWriter(new FileWriter("FILE_PATH_HERE"))){
br.write("STUFF_TO_WRITE_HERE");
} catch(IOException e){
}
With this try-with-resources statement, all of the closing file effort is done automatically.
This will only work for Java 7 or higher.
You have to flush your output. This can be done directly by calling writer.flush().

The FileReader cannot find my text file

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();
}

Unable to open a file using FileReader in java applet while the programs runs without any error in Eclipse IDE

I'm writing an applet. When i am running the code in command prompt it shows a file not found exception. The program is running pretty fine in Eclipse IDE. Can anyone tell what could be the error?
Frame frame= new Frame();
FileDialog openfile= new FileDialog(frame,"Select a file", FileDialog.LOAD);
openfile.setVisible(true);
String file=openfile.getFile();
System.out.println(file);
try{
FileReader f= new FileReader(file);
BufferedReader br= new BufferedReader(f);
Scanner in=new Scanner(br);
while(in.hasNextInt()){
n=in.nextInt();
count++;
sum += n;
System.out.println(n);
}
System.out.println("Count:" + count);
This happens if the target file is not in the same directory as your application.
Use String file = openfile.getDirectory() + File.separator + openfile.getFile(); to get the absolute path to the target file.
You need to specify the directory
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class FileReader1 {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
int sum=0,count=0,n;
Frame frame= new Frame();
FileDialog openfile= new FileDialog(frame,"Select a file", FileDialog.LOAD);
openfile.setVisible(true);
String dir=openfile.getDirectory();
String file = openfile.getFile();
File ff = new File(dir+file);
FileReader fr = null;
BufferedReader br = null;
Scanner in = null;
System.out.println(dir+file);
try{
fr = new FileReader(ff);
br = new BufferedReader(fr);
in=new Scanner(br);
while(in.hasNextInt()){
n=in.nextInt();
count++;
sum += n;
System.out.println(n);
}
System.out.println("Count:" + count);
}catch(Exception e){
System.out.println("Exception"+e);
}finally{
fr.close();
br.close();
in.close();
}
}
}

How do make output have more than one string (Java)

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);

Categories

Resources