Java reading files - java

I am trying to learn file reading and writing, but I tried it with BufferedReader, and Scanner, it will always show the exception message. I followed the steps in the book tho. Not sure what went wrong.
package fileIO;
import java.io.*;
import java.util.*;
public class files {
public static void main(String[] args) {
String line = "";
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("Shadow.txt"));
while(br.readLine() != null){
line += br.readLine();
System.out.println(line);
}
}catch(FileNotFoundException e){
System.err.println("File not found");
}catch(Exception e){
System.out.println("Throwing exception");
}
}
}

Change your while a little bit:
while( (line = br.readLine() ) != null ) {
System.out.println(line);
}

This works for me:
import java.io.*;
class Test {
public static void main(String[] args) {
Printer.print("Shadow.txt");
}
}
public class Printer {
public static void print(String filename) {
String line;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
while ((line = br.readLine()) != null) System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.close();
}
}
}
I upgraded you to a try-with-resources, and fixed your while-loop. Hopefully it's also an example of how to write more modular code.

Related

No output from a program that compiles

I can't wrap my head around why I get zero output... The code looks correct to me, and it compiles with no problem (except for the lack of output). I have tried with absolute path. The text file is stored in the same folder as the class. Am I missing something obvious?
public class File {
public static void main(String[] args) throws FileNotFoundException {
String filename = "./inputD2.txt";
readFile(filename);
System.out.println( readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
}
catch (Exception e) {
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
return null;
}
}
}
package com.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class FileReaderTest {
public static void main(String[] args) {
String filename = "F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt";
System.out.println("Reading from the text file" + " " + readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records;
try {
records = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
} catch (Exception e) {
System.err.println("Exception occurred trying to read '%s'." + filename);
e.printStackTrace();
return null;
}
}
}
I modified your code and got the desired output. Use the full path of the text file, here
F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt
is my full path.
Changes:
Changed the classname
Given full path of the text file
Using java 1.8 (above 1.5 is required)

I am making the bible app and I want to print a particular chapter and highlight a particular line

I am trying to do same in Eclipse to print a text file and highlight a particular line, but am only able to read text file and not the line in it. Following is my code:
import java.io.*;
public class Bible {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("temp.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Correct code to read a file line by line is
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Now comes the code to highlight.
There are multiple options to do it.
Use html codes in file e.g.
origString = origString.replaceAll(textToHighlight,"<font color='red'>"+textToHighlight+"</font>");
Textview.setText(Html.fromHtml(origString));
Use spannable texts
String text = "Test";
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 14, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanText);
Use some third party library
EmphasisTextView and
Android TextView Link Builder

Access external files

Am using nio2 to read the external file in my desktop using eclipse. I am getting the exception for the following code.
"java.nio.file.NoSuchFileException: C:\Users\User\Desktop\JEE\FirstFolder\first.txt"
Kindly advise how to resolve it? Tried using command prompt also. Getting the same exception.
public class ReadingExternalFile {
public static void main(String[] args) {
Path p1= Paths.get("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
System.out.println(p1.toString());
System.out.println(p1.getRoot());
try(InputStream in = Files.newInputStream(p1);
BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
}
}
I dont understand why you are using a Path object, you can simply make the file using the File object and just using the string as the path, and then wraping it in a file reader object then wrapping that in a buffered reader, the end should look something like this:
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine());
bfr.close();
} catch (IOException e){
e.printStackTrace();
}
}
don't forget to close your streams after reading and writing, also use readable names (don't do what I've done, use meaningful names!)
Try below code hope this will help you.
Path p1= Paths.get("C:\\Users\\user\\Desktop\\FirstFolder\\first.txt");
try(
BufferedReader reader = Files.newBufferedReader(p1, Charset.defaultCharset()))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
Try this.
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:\\Users\\User\\Desktop\\FirstFolder\\first.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();
}
}
}
}
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader freader = new FileReader(file);
BufferedReader bufreader = new BufferedReader(freader);
System.out.println(bufreader.readLine());
bufreader.close();
} catch (IOException e){
e.printStackTrace();
}
}

Java i/o reading a text while hiding specific words

How would you read the following text while hiding the word SECRET each times it appears ?
here is the text :
this line has a secret word.
this line does not have a one.
this line has two secret words.
this line does not have any.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class BufferedReadertest {
public static void main(String[] args) {
ArrayList <String>list = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("secretwords.txt"));
while ((sCurrentLine = br.readLine()) != null) {
list.add(sCurrentLine);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Do you mean like
System.out.println(list.get(i).replaceAll("SECRET", "******");
I'm n seeing the need to use an ArrayList. Replace SECRET and print the message when iterating the buffered reader.
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("secretwords.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.replaceAll("SECRET", ""));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
if(line.indexOf("SECRET") > -1){
System.out.println("Has Secret");
continue;
}

Java syntax error buffered reader

I'm writing a class that just reads a text file and prints out the lines. I'm getting an error on the line containing BufferedReader rd = new BufferedReader(new FileReader("file.txt")); saying that Syntax error on token ";", { expected after this token. I've tried placing it within a method, and within a try catch block as it recommends but then I'm unable to resolve the rd variable. I'm using the acm package so some of the other syntax may look different but I receive no other errors. Any help would be greatly appreciated =)
import acm.program.*;
import acm.util.*;
import java.io.*;
import java.util.*;
public class FileReading extends ConsoleProgram {
BufferedReader rd = new BufferedReader(new FileReader("file.txt"));
try {
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
rd.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
Code blocks like this should be embodied inside a method or a static clause. Something like:
public class FileReading extends ConsoleProgram {
public void readFile(){
BufferedReader rd = null;
try {
rd = new BufferedReader(new FileReader("file.txt"));
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
}catch (IOException ex) {
throw new ErrorException(ex);
}finally{
try{
rd.close();
}catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
}
As answered by others, you cant provide your code in the general part of the class, it has to be within a method or static block.
By putting the code block in the constructor the problem went away.
See below for example.
import acm.program.*;
import acm.util.*;
import java.io.*;
import java.util.*;
public class FileReading extends ConsoleProgram {
public FileReading()
{
BufferedReader rd = new BufferedReader(new FileReader("file.txt"));
try {
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
rd.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
}
Create a method... and inside that do this... Not directly inside the class
eg:
public void go()
{
BufferedReader rd = new BufferedReader(new FileReader("file.txt"));
try {
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
rd.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
}

Categories