File not opening in Java - java

Im trying to read a simple text file with contents
input.txt
Line 1
Line 2
Line 3
But it always goes to the exception and prints Error.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR");
}
}
}
Im using Eclipse as my IDE if that makes a difference. I've tried this code on http://www.compileonline.com/compile_java_online.php
and it runs fine, why wont it run in Eclipse?

give complete file path like "C:\\folder_name\\input.txt" or place input.txt inside src directory of eclipse project.

public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(
new FileReader("input.txt")); //<< your problem is probably here,
//More than likely you have to supply a path the input file.
//Something like "C:\\mydir\\input.txt"
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR"); //This tells you nothing.
System.out.println(e.getMessage()); //Do this
//or
e.printStackTrace(); //this or both
}
}
}

You most likely have a bad path. Consider this main instead:
public class Main {
public static void main(String args[]) throws Exception {
List<String> text = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}
}
The "throws Exception" addition allows you to focus on the code, and consider better error handling later. Also consider using File f = new File("input.txt") and use that, because it allows you to print out f.getAbsolutePath() which tells you the filename it was actually looking for.

Changing input.txt to src\\input.txt solved the problem!
I guess it was because the current directory isnt actually the src folder its the parent,
Thanks for the help!

Related

BufferedReader not reading whole online XML file

public static void main(String[] args) throws MalformedURLException, IOException
{
// TODO code application logic here
URL link1 = new URL("xmlFileHere");
InputStream xml = link1.openStream();
InputStreamReader reader = new InputStreamReader(xml);
BufferedReader reader1 = new BufferedReader(reader);
while(reader1.readLine()!= null)
{
System.out.println(reader1.readLine());
}
}
Hello. As you can see my BufferedReader is not reading the whole online XML file, I don't know why. Any idea why this happens?
Thank you.
while(reader1.readLine()!= null) // reading here
{
System.out.println(reader1.readLine()); // and here
}
You are skipping a line each time you loop...
Do,
String line=null;
while((line=reader1.readLine())!= null) // reading here
{
System.out.println(line); // and displaying here
}
Consider using Scanner which thanks to hasNextLine() method makes iterating more intuitive.
Scanner scanner = new Scanner(reader1);
while (scanner.hasNextLine() ) {//check if next line exists
System.out.println(scanner.nextLine());//use this next line
}
scanner.close();
I prefer this idiom
for (String curLine; (curLine=reader1.readLine()) != null;) {
System.out.println(curLine);
}
it's good because curLine var is needed only inside loop
Change this in your code.
String curLine = "";
while((curLine=reader1.readLine())!= null)
{
System.out.println(curLine);
}
reader1.readLine() will read your line in while loop and again inside while loop which create problem in not displaying whole XML file.
Change the while loop.
String line;
while( (line=reader1.readLine() ) != null)
{
System.out.println(line);
}

Basic Java IO, always throwing exception

I'm new to Java and am trying to write a program that has one argument, the path of a text file. The program will locate the text file and print it out to the screen. Eventually I'm going to build this to format the given text file and then print it out to an outfile, but I'll get there later.
Anyways my program is always throwing and IOException and I'm not sure why. Given the argument C:\JavaUtility\input.txt , I receieve "Error, could not read file" during runtime. My code is located below.
import java.io.*;
public class utility {
public static void main(String[] path){
try{
FileReader fr = new FileReader(path[0]);
BufferedReader textReader = new BufferedReader(fr);
String aLine;
int numberOfLines = 0;
while ((aLine = textReader.readLine()) != null) {
numberOfLines++;
}
String[] textData = new String[numberOfLines];
for (int i=0;i < numberOfLines; i++){
textData[i] = textReader.readLine();
}
System.out.println(textData);
return;
}
catch(IOException e){
System.out.println("Error, could not read file");
}
}
}
[EDIT] Thanks for all the help everyone! So given my end goal, I thought it would still be useful to find the number of lines and store in a finite array. So I ended up writing two classes. The first, ReadFile.java found the data I wanted and handles most of the reading. The second FileData.java invokes the methods in ReadFile and prints out. I've posted them below incase someone later finds them useful.
package textfiles;
import java.io.*;
public class ReadFile {
private String path;
public ReadFile(String file_path){
path = file_path;
}
int readLines() throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for(int i=0; i < numberOfLines; i++){
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args)throws IOException{
String file_name = args[0];
try{
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
for(int i=0; i < aryLines.length; i++){
System.out.println(aryLines[i]);
}
}
catch (IOException e){
System.out.println(e.getMessage());
}
}
}
You're at the end of the file. When you determine the number of lines in the file, you've read until the end of the file,and the EOF Flag is set. [Edit: As #EJP notes below, BufferedReader returns null reading past the end of a file. The fact your reader isn't where you want it, however, remains true.] In the past, I've hacked around this simply by closing and re-opening the file. Alternatively, look into Array Lists or simple Lists. They're dynamically re-sizing, so you don't need to know the number of lines in the file ahead of time.
As mentioned by #mikeTheLiar you are at End Of File. BufferedReader reference is File Handler with an internal cursor pointing to current position in file. As you fire readLine() method, the pointer reads characters till it reaches new line character, returning the string. The pointer is set to new position. Once you read all the lines then readLine() returns null. After that if you call readLine() it will throw IOException. As noted by #EJP
One of the best coding rules while using IO API is to always check for EOF condition - the way you have in first loop. Once you reach EOF after that you should not call read method on the same reference without resetting the cursor - this can be done by calling reset() method.
IMHO, in your case there is no need for second loop. You can achieve the functionalty using one loop only.
import java.io.*;
import java.util.ArrayList;
public class utility {
public static void main(String[] path){
try{
FileReader fr = new FileReader(path[0]);
BufferedReader textReader = new BufferedReader(fr);
String aLine;
int numberOfLines = 0;
ArrayList readLines = new ArrayList();
while ((aLine = textReader.readLine()) != null) {
numberOfLines++;
readLines.add(aLine);
}
//Assuming you need array of lines, if not then you can print the lines directly in above loop
String[] textData = readLines.toArray();
System.out.println(textData);
return;
}
catch(IOException e){
System.out.println("Error, could not read file");
}
}
}
EDIT
I tried your code - it is working fine and printing the array reference. As suggested in comments the problem is with source (file might not be readable due to security or any other reason) - if you can print the exception message and get the exact line number where exception is thrown it would be helpful.
Couple of observations apart from the IO exception:
You are trying to open the file twice. readLines() method is called from within OpenFile(). Following the sequence of code file is first opened in OpenFile() when you create textReader. After that you are calling readLines() which is again trying to open the file when you create file_to_read.
You should try to avoid that and in your flow you should call int numberOfLines = readLines(); before FileReader fr = new FileReader(path);
Again IMHO there should be only one method and you should iterate over the file only once - both from efficience/performance and code maintainability perspective. You can change your ReadFile class as follows:
package textfiles;
import java.io.*;
import java.util.ArrayList;
public class ReadFile {
private String path;
public ReadFile(String file_path){
path = file_path;
}
//You need not have separate file for counting lines in file
//Java provides dynamic sized arrays using ArrayList
//There is no need to count lines
public String[] OpenFile() throws IOException{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
ArrayList fileLines = new ArrayList();
String readLine = textReader.readLine();
while(readLine != null){
fileLines.add(readLine);
readLine = textReader.readLine();
}
textReader.close();
return fileLines.toArray();
}
}
Another small observation: in some places the java variable naming conventions are not followed. OpenFile() method should be openFile() and file_to_read should be fileToRead
Contrary to several answers here, readLine() does not throw an exception at end of file, it just keeps returning null. Your problem is being masked by another one. Never just make up your own error messages. Always print the one that comes with the exception. If you had done that you would probably have found the problem immediately. Almost certainly you weren't able to open the file at all, either because it wasn't there or you didn't have read access. The exception will tell you.

How to populate an ArrayList from words in a text file?

I have a text file containing words separated by newline , like the following format:
>hello
>world
>example
How do i create an ArrayList and store each word as an element?
You can use apache commons FileUtils.readLines().
I think the List it returns is already an ArrayList, but you can use the constructor ArrayList(Collection) to make sure you get one.
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
File file = new File("names.txt");
ArrayList<String> names = new ArrayList<String>();
Scanner in = new Scanner(file);
while (in.hasNextLine()){
names.add(in.nextLine());
}
Collections.sort(names);
for(int i=0; i<names.size(); ++i){
System.out.println(names.get(i));
}
The simplest way is to use Guava:
File file = new File("foo.txt");
List<String> words = Files.readLines(file, Charsets.UTF_8);
(It's not guaranteed to be an ArrayList, but I'd hope that wouldn't matter.)
You read the file line-by-line, create an ArrayList for Strings, and add line.substring(1) to the defined ArrayList if line.length>0.
I put the file at "C:\file.txt"; if you run the following it fils an ArrayList with the words and prints them.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:\\file.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<String>();
String line = br.readLine();
while(line != null) {
lines.add(line.replace(">", ""));
line = br.readLine();
}
for(String l : lines) {
System.out.println(l);
}
}
}
I'm sure they're lots of libraries that do this with 1 line, but here's a "pure" Java implementation:
Notice that we've "wrapped"/"decorated" etc. a standard FileReader (which only has read one byte at a time) with a BufferedReader which gives us a nicer readLine() method.
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("test.txt"),
Charset.forName("ISO-8859-1")));
List<String> lines = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
System.out.println(lines);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}

Modifying existing file content in Java

I want to replace the second line file content, can somebody help please based on the below file format and listener method.
1324254875443
1313131
Paid
0.0
2nd line is long and want to replace to currentTimeMillis().
/************** Pay Button Listener **************/
public class payListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
try {
FileReader fr = new FileReader("Ticket/" + ticketIDNumber + ".dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Ticket/" + ticketIDNumber + ".dat");
BufferedWriter bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line.replace(System.currentTimeMillis();
lines.add(line);
bw.write(line);
} //end if
} //end try
catch (Exception e) {
} //end catch
} //end while
}//end method
Although this question is very old I'd like to add that this can be achieved much easier since Java 1.7 with java.nio.file.Files:
List<String> newLines = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
if (line.contains("1313131")) {
newLines.add(line.replace("1313131", ""+System.currentTimeMillis()));
} else {
newLines.add(line);
}
}
Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);
As proposed in the accepted answer to a similar question:
open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.
Based on your implementation, something similar to:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "try.dat";
String tmpFileName = "tmp_try.dat";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line = line.replace("1313131", ""+System.currentTimeMillis());
bw.write(line+"\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
I could suggest to use Apache Commons IO library. There you'll find the class org.apache.commons.io.FileUtils. You can use it:
File file = new File("... your file...");
List<String> lines = FileUtils.readLines(file);
lines.set(1, ""+System.currentTimeMillis());
FileUtils.writeLines(file, lines);
This code reads entire file contents into a List of Strings and changes the second line's content, then writes the list back to the file.
I'm not sure reading and writing the same file simultaneously is a good idea. I think it would be better to read the file line by line into a String array, replace the second line and then write the String array back into the file.

java program Inetaddress

The question I have been asked is too
write java program that reads IP address from input file and writes the corresponding host names in the output file and vice versa.
here is my code:
import java.net.*;
import java.io.*;
public class hw
{
public static void main(String args[])
{
try{
FileReader f= new FileReader("w.txt");
BufferedReader r = new BufferedReader(f);
FileWriter o = new FileWriter("out.txt");
PrintWriter p = new PrintWriter(o);
String line = r.readLine();
String hn=line;
String IP;
InetAddress d=InetAddress.getByName(hn);
while(line !=null)
{
hn=d.getByName(line);
p.println(hn);
IP=d.getHostName();
p.println(IP);
}
r.close();
p.close();
}
catch(FileNotFoundException e )
{System.out.println("file not found");}
catch(IOException e)
{System.out.println("io error "+e.getMessage());}
}//main
}//class
I guess your while loop never terminates. Usually I read in a loop like this:
while ((line = r.readLine()) != null) {
// process line, i.e.
InetAddress ia = InetAddress.getByName(line.trim());
// etc.
}
Also you might consider putting your close statements into the finally block for good form.
kevin corrected your loop error , as for your second question
I suggest you read this tutorial about reading and writing files Using stream io

Categories