As my Previous Question I used read() from java.io.FileInputStream and read(); provide output in same line without line terminated. After that I used readLine() from java.io.BufferedReader and got output in different line with line terminated. I explored readLine() method and I got this line from Java API Docs
Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage return
followed immediately by a linefeed.
After reading above quote from Java Docs, I modify my read(); method program to terminate line without readLine() method. But failed,
Here is the Modified code.(that I want to use for line terminated)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BoxDemo {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
if((char)c=='\r' || (char)c=='\n') {
out.write('\n');
} else {
out.write(c);
}
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Here is readLine(); method code that give output with line terminated.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class BoxDemo {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
As reference, here's the output of your first code with the same xanadu.txt file as your last question:
Input:
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
Output:
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
So there's a redundant line break somewhere. This comes from the following if condition:
if((char)c=='\r' || (char)c=='\n') {
out.write('\n');
I'm guessing you are running this on a Windows machine where the line terminator is \r\n, so the characters \r and \n are actually both read, resulting in \n being written twice.
Again, since you seem to be using Windows, depending on your editor, it might not format \n as line breaks and outputs everything on a single line.
You can correct this by writing
out.write('\r');
out.write('\n');
explicitely.
With having said that, I do not recommend you to use this. You should use System.lineSeparator() where possible, as this results in the system dependant correct line separator.
Related
I am working on a program that evaluates lisp expressions using a stack implemented by either an array or linked list. I need to read the file in from the first line from right to left. Currently I am reading it in from left to right but I do not understand how I can switch it around. Any help you can give me is greatly appreciated! Thank you!
**I know the program is nowhere near complete, I just need to accomplish this before I can continue.
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.*;
import java.io.BufferedReader;
public class A2Q5{
private static Scanner in;
public static void main (String [] args)
{
if(args.length != 2) {
System.out.println("Please execute as: java A2Q5 type infile");
}
BoundedStack<Double> stack;
if(args[0].equals("0"))
stack = new BSArray<Double>(20);
else
stack = new BSLinkedList<Double>();
// The name of the file to open.
String fileName = args[1];
// This will reference one line at a time
//char c = null;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
for (int i = line.length() - 1; i >= 0; i--){
line.charAt(i);
System.out.println(line.charAt(i));
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file " + fileName);
}
catch(IOException ex) {
System.out.println("Error reading file " + fileName);
}
}
}
Drop the use of FileInputStream and use BufferedReader that you already prepared but never use. Use its method readLine to read info from your file line by line. Once you got an individual line you can iterate through it character by character from the end of the String to its beginning. This is exactly what you want.
I want to merge huge files containing strings into one file and tried to use nio2. I do not want to load the whole file into memory, so I tried it with BufferedReader:
public void mergeFiles(filesToBeMerged) throws IOException{
Path mergedFile = Paths.get("mergedFile");
Files.createFile(mergedFile);
List<Path> _filesToBeMerged = filesToBeMerged;
try (BufferedWriter writer = Files.newBufferedWriter(mergedFile,StandardOpenOption.APPEND)) {
for (Path file : _filesToBeMerged) {
// this does not work as write()-method does not accept a BufferedReader
writer.append(Files.newBufferedReader(file));
}
} catch (IOException e) {
System.err.println(e);
}
}
I tried it with this, this works, hower, the format of the strings (e.g. new lines, etc is not copied to the merged file):
...
try (BufferedWriter writer = Files.newBufferedWriter(mergedFile,StandardOpenOption.APPEND)) {
for (Path file : _filesToBeMerged) {
// writer.write(Files.newBufferedReader(file));
String line = null;
BufferedReader reader = Files.newBufferedReader(file);
while ((line = reader.readLine()) != null) {
writer.append(line);
writer.append(System.lineSeparator());
}
reader.close();
}
} catch (IOException e) {
System.err.println(e);
}
...
How can I merge huge Files with NIO2 without loading the whole file into memory?
If you want to merge two or more files efficiently you should ask yourself, why on earth are you using char based Reader and Writer to perform that task.
By using these classes you are performing a conversion of the file’s bytes to characters from the system’s default encoding to unicode and back from unicode to the system’s default encoding. This means the program has to perform two data conversion on the entire files.
And, by the way, BufferedReader and BufferedWriter are by no means NIO2 artifacts. These classes exists since the very first version of Java.
When you are using byte-wise copying via real NIO functions, the files can be transferred without being touched by the Java application, in the best case the transfer will be performed directly in the file system’s buffer:
import static java.nio.file.StandardOpenOption.*;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MergeFiles
{
public static void main(String[] arg) throws IOException {
if(arg.length<2) {
System.err.println("Syntax: infiles... outfile");
System.exit(1);
}
Path outFile=Paths.get(arg[arg.length-1]);
System.out.println("TO "+outFile);
try(FileChannel out=FileChannel.open(outFile, CREATE, WRITE)) {
for(int ix=0, n=arg.length-1; ix<n; ix++) {
Path inFile=Paths.get(arg[ix]);
System.out.println(inFile+"...");
try(FileChannel in=FileChannel.open(inFile, READ)) {
for(long p=0, l=in.size(); p<l; )
p+=in.transferTo(p, l-p, out);
}
}
}
System.out.println("DONE.");
}
}
With
Files.newBufferedReader(file).readLine()
you create a new Buffer everytime and it gets always reset in the first line.
Replace with
BufferedReader reader = Files.newBufferedReader(file);
while ((line = reader.readLine()) != null) {
writer.write(line);
}
and .close() the reader when done.
readLine() does not yield the line ending ("\n" or "\r\n"). That was the error.
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.write("\r\n"); // Windows
}
You might also disregard this filtering of (possibly different) line endings, and use
try (OutputStream out = new FileOutputStream(file);
for (Path source : filesToBeMerged) {
Files.copy(path, out);
out.write("\r\n".getBytes(StandardCharsets.US_ASCII));
}
}
This writes a newline explicitly, in the case that the last line does not end with a line break.
There might still be a problem with the optional, ugly Unicode BOM character to mark the text as UTF-8/UTF-16LE/UTF-16BE at the beginning of the file.
I could not find an explanation and those I found I am unsure of. So please confirm my doubts:
I am reading through a file using a while loop and if the line in the file is empty it skips and goes to next line. I just want to make sure the code I am using is correct for the what I just described:
while((strLine = reader.readLine())!= null) <----- While loop that is suppose to read Line by Line
{
if (strLine.isEmpty() == false) <----- Check for empty Line
{
/** My Code **/
}
else
{
/** My Code **/
}
}
Yes! What you are doing is what you want to do. You can just try compiling it yourself, you know. Trial and error. If you could not figure out how to use the reader, as the other answers propose, here you go:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Trial {
public static void main(String[] args) throws IOException {
String strLine;
BufferedReader reader = new BufferedReader(new FileReader(
"/home/user234/folder1/filename"));
while ((strLine = reader.readLine()) != null) {
if (!strLine.isEmpty()) {
System.out.println("notEMPTY");
} else {
System.out.println("EMPTY");
}
}
}
}
yes. it will work fine.
while(/* While scanner has next line */)
{
line = scanner.nextLine();
if( /* line is not equal to null */) {
/* perform code */
}
}
The logic shown in the above code makes sense to what you have described. It should perform what you desire.
The Java Reader does not have a readline() method.
If you want to do specific parsing of tokens you should use the Scanner. Scanner has a nextLine() method to grab each line, but throws an Exception if there is no next line. Therefore you should use Scanner.hasNextLine() for your while condition.
Scanner s = new Scanner("filename.txt");
String line;
while(s.hasNextLine()){ // check for next line
line = s.nextLine(); // get next line
if(line == ""){ // check if line is empty
System.out.println("Empty");
} else {
System.out.println("Not Empty:" + line);
}
}
Here's a live Example using Ideone.
EDIT: The BufferedReader does have a readline() method, as used by #natsirun. Although for any file parsing more complicated than line reading you would prefer the Scanner.
If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.
may i know why i am unable to read next line in a .txt file when i upload it.
it happens to all the .txt file that i try to upload and then system.out.println() with.
in my text file it contains : cats,dogs,monkey ( each in one line ) .. but the value out put is:
[Monkey][Monkey, null][Monkey, null, null][Monkey, null, null, null][Monkey, null, null, null, null][Monkey, null, null, null, null, null][Monkey, null, null, null, null, null, null]
needs help on this.
thank you.
and wondering why i can read .txt file and not .doc. need advise on this as well.
import java.awt.List;
import java.io.*;
import java.util.ArrayList;
import javax.imageio.IIOException;
import javax.swing.JFileChooser;
public class searchforCapitalLetter {
public static void main(String[] args) throws IOException{
try {
// file chooser
JFileChooser chooser=new JFileChooser();
int returnVal = chooser.showOpenDialog(null);{
if(returnVal == JFileChooser.APPROVE_OPTION)
{ File f = chooser.getSelectedFile();}
FileInputStream fin = new FileInputStream(chooser.getSelectedFile());
DataInputStream din = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(din));
ArrayList<String>list =new ArrayList<String> ();
if ((br.readLine()) != null) {
while (br.readLine() != " ") {
list.add(br.readLine());
System.out.print (list);
} br.close() ;
}//closes if statement
} // closes method dialog
} // closes try method
catch (FileNotFoundException e) {
e.printStackTrace();
} // closes catch method
} // closes method body
} // closes class method
Per the bufferedreader api:
public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a
carriage return ('\r'), or a carriage return followed immediately by a
linefeed.
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached
Throws: IOException - If an I/O error occurs
Note that your code is making a few errors:
1) it is calling readline() once to check a return value and again to use the return value. The first call (in the while condition) removes the current value from the buffer, so your are dropping every other line.
2) you are using the wrong comparison to see if there's data remaining. x != y, where both x and y are objects, checks for pointer equality - is the memroy location where x is allocated the same as the memory location where y is allocated. what you really want is to store the value in a variable.
For example:
BufferedReader in = ...;
String s = in.readLine();
while(s!=null){
...
s = in.readLine();
}
The reason you can't use .doc is because .doc files are formatted, and as such, have some things your code would have to parse to read from them.
As far as the weird printing goes, you read the code twice before you even get to printing it (each time you call .readLine, it moves the scanner to the next line). Try the following code:
ArrayList<String>list =new ArrayList<String> ();
String currentLine;
while ((currentLine = br.readLine()) != null) {
list.add(currentLine);
System.out.println(currentLine);
} br.close() ;
}
That will keep track of the current line in a variable, rather than repeatedly moving the scanner to the next line. The other issue was it will be null, not " ", when the end of the file is reached
A classic BufferedReader to read content from a file.
this our file to read with Java:
This is the content to write into file
This is the content to write into file
package com.stackoverflow;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile{
private static final String FILENAME = "D:\\test\\filename.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
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();
}
}
}
}
Output :
This is the content to write into file
This is the content to write into file