Access external files - java

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

Related

Read a text file in windows directory outside eclipse project

My Java project is located at C:\eclipse\workspace\cgw
Is it possible to read a text file located on C:\CGW\conexao\conexao.txt
File file = new File("C:\CGW\conexao\conexao.txt");
You can read a file anywhere on your computer, here is an example using Java BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample1 {
private static final String FILENAME = "E:\\test\\filename.txt";
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();
}
}
}
}
View tutorial useful to read from files.

Java reading files

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.

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

Making Java I / O and change the file to split in java

I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Close file in finally block doesn't work

try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
} finally {
fr.close();
}
The fr.close() shows an error:
fr cannot be resolved
I had read that closing a file in the finally block is a good practice.
What is that am doing wrong?
The variable fr only has scope within the try block. It is out of scope in the finally block. You need to declare it before the try block:
FileReader fr = null;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
// This is unrecoverable. Just report it and move on
e.printStackTrace();
}
}
}
This is quite a common pattern of code, so it's good to remember it for future similar situations.
Consider throwing IOException from this method - printing track traces isn't very helpful to callers, and you wouldn't need the nested try catch around fr.close()
Now finally block is not needed,
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);){
String line = null;
}
} catch(FileNotFoundException fnf) {
fnf.printStackTrace();
}
now automatically close your readers
You have a problem with your scopes. If you really want to use that syntax you should fix it like this:
FileReader fr = null;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
} finally {
if( fr != null)
fr.close();
}
that way, fr will exist in the finally's block scope.
public static void main(String[] args) throws IOException{
FileReader file1 = null;
try{
file1 = new FileReader("blaaa.txt");//this file does not exist
}
catch (FileNotFoundException e){}
catch (IOException e) {e.printStackTrace();}
finally {
try{file1.close();}
catch (NullPointerException e){
}
finally {
System.out.println("Thank you, please try again");
}
}
}

Categories