I have the following code:
public static void main(String[] args) throws Exception {
String s = "";
StringBuilder sb = new StringBuilder();
File file = new File("C:\\New\\r.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
while(in.readLine() != null) {
sb.append(in.readLine());
}
System.out.println(sb);
s = sb.toString();
byte[] b = s.getBytes();
for(int i = 0; i < b.length; i++) {
if(b[i] == 1){ b[i]=0; }
if(b[i] == 0){ b[i]=1; }
}
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
dos.write(b);
in.close();
fos.close();
dos.close();
}
I get a return of null when I run this program. Maybe I must elevate the program? Help would be appreciated.
Change:
while(in.readLine()!=null)
to:
while((s = in.readLine())!=null)
and then:
sb.append(s);
When you call in your code to in.readLine() twice - you're reading two lines but printing only the second in each iteration.
You're throwing away every odd line:
while(in.readLine()!=null)
{
sb.append(in.readLine());
}
If r.txt only contains one line, you will get the string "null" in the StringBuffer, because the first line of StringBuffer.append does this:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
....
}
If there are two lines, you will get the first line with "null" at the end of the line.
The following will append all lines from the file to the StringBuffer:
String line = null;
while((line = in.readLine()) != null)
{
sb.append(line);
}
your code
while(in.readLine() != null) {
sb.append(in.readLine());
}
change with it
while ((s = in.readLine()) != null)
{
sb.append(s);
}
Related
I want to use mark() and reset() method to read the line before divider.
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
while ((line = br.readLine()) != null) {
boolean endOfObj = false;
while (!line.trim().contains(DIVIDER)) {
br.mark(line.length());
line = br.readLine(); //return next line
}
br.reset();
line = br.readLine();
but line variable value is not the previous line of divider.
what is my problem is .
thank you
Could you try using the following code? I tidied up your code a bit, and put it into a method called getPreviousLine(). I got the feeling that you were getting hung up on using mark() and reset(), so I just relied on pure logic and state to find the line before the divider. If no divider is found, the method will return null.
String getPreviousLine(String PATH) {
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
boolean endOfObj = false;
String previousLine = br.readLine();
if (previousLine == null) {
return null;
}
while ((line = br.readLine()) != null) {
if (line.trim().contains(DIVIDER)) {
endOfObj = true; // found the divider; break
break;
} else {
previousLine = line; // advance your line pointer
}
}
if (endOfObj) {
return previousLine;
} else {
return null;
}
}
I have the following code:
in = new BufferedReader(new FileReader("D/sample.txt"));
String str;
while ((str = in.readLine()) != null)
{
process(str);
}
Say sample.txt contains 'n' number of lines. I am passing the String object to another function process in the same class.The function process contains following code:
public void process(String s) {
String elements = s;
System.out.println(elements);
How can i print only the first line or the line that i wish to be printed. Please help.
If I understand you, you could pass in the lineCount - that is
in = new BufferedReader(new FileReader("D:/sample.txt")); // <-- added ':'
String str;
int lineCount = 0;
while ((str = in.readLine()) != null) {
process(str, lineCount++);
}
And then
public void process(String s, int lineCount) {
if (lineCount == 0) { // <-- only the first line.
System.out.println(s);
}
}
You can pass a flag to your process method to advise it to print or not. Something like this:
public void process(String s, boolean print) {
String elements = s;
if(print)
System.out.println(elements);
}
Just add a counter to your loop, and only call process on the lines you want to process.
in = new BufferedReader(new FileReader("D/sample.txt"));
String str;
int readLines = 0;
while ((str = in.readLine()) != null)
{
readLines++;
if(readLines == 1) //Only process first line
process(str);
}
Call process(str) only for the line you wish:
int lineToPrint = 1;
in = new BufferedReader(new FileReader("D/sample.txt"));
String str;
int i =1;
while ((str = in.readLine()) != null)
{
if (i==1){
process(str);
}
i++;
}
I am trying to compare two .txt files (i.e their contents), but when I execute this code my application goes into an infinite loop. Why?
public int compareFile(String fILE_ONE2, String fILE_TWO2)throws Exception
{
File f1 = new File(fILE_ONE2); //OUTFILE
File f2 = new File(fILE_TWO2); //INPUT
FileReader fR1 = new FileReader(f1);
FileReader fR2 = new FileReader(f2);
BufferedReader reader1 = new BufferedReader(fR1);
BufferedReader reader2 = new BufferedReader(fR2);
String line1 = null;
String line2 = null;
int flag=1;
while ((flag==1) &&((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null))
{
if (!line1.equalsIgnoreCase(line2))
flag=0;
else
flag=1;
}
reader1.close();
reader2.close();
return flag;
}
I converted your code into a main program. There is no infinite loop in this code.
I am assuming you are comparing 2 text files of a small-ish size.
import java.io.*;
public class Diff {
public static void main(String[] args) throws FileNotFoundException, IOException {
File f1 = new File(args[0]);// OUTFILE
File f2 = new File(args[1]);// INPUT
FileReader fR1 = new FileReader(f1);
FileReader fR2 = new FileReader(f2);
BufferedReader reader1 = new BufferedReader(fR1);
BufferedReader reader2 = new BufferedReader(fR2);
String line1 = null;
String line2 = null;
int flag = 1;
while ((flag == 1) && ((line1 = reader1.readLine()) != null)
&& ((line2 = reader2.readLine()) != null)) {
if (!line1.equalsIgnoreCase(line2))
flag = 0;
}
reader1.close();
reader2.close();
System.out.println("Flag " + flag);
}
}
I ran it on 2 small different text files. This is the output.
javac Diff.java && java Diff a.txt b.txt
Flag 0
If you think you have an infinite loop, the issue might be elsewhere.
The code looks good, no infinite loops. You can remove irrespective check in the code and can update the code as below:
int flag=1;
while (((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null))
{
if (!line1.equalsIgnoreCase(line2))
{
flag=0;
break;
}
}
As the return type of the method is integer than it will return 0 if different and 1 if equal.
Assuming text file inputs, an alternative implementation to the while loop:
while (true) // Continue while there are equal lines
{
line1 = reader1.readLine();
line2 = reader2.readLine();
if (line1 == null) // End of file 1
{
return (line2 == null ? 1 : 0); // Equal only if file 2 also ended
}
else if (line2 == null)
{
return 0; // File 2 ended before file 1, so not equal
}
else if (!line1.equalsIgnoreCase(line2)) // Non-null and different lines
{
return 0;
}
// Non-null and equal lines, continue until the input is exhausted
}
The first else if is not necessary, but it is included for clarity purposes. Otherwise, the above code could be simplified to:
while (true) // Continue while there are equal lines
{
line1 = reader1.readLine();
line2 = reader2.readLine();
if (line1 == null) // End of file 1
{
return (line2 == null ? 1 : 0); // Equal only if file 2 also ended
}
if (!line1.equalsIgnoreCase(line2)) // Different lines, or end of file 2
{
return 0;
}
}
The loop should be placed in a try/finally block, to assure that the readers are closed.
Above method by Jess will fail if file2 is same as file1 but has an extra line at the end.
This should work.
public boolean compareTwoFiles(String file1Path, String file2Path)
throws IOException {
File file1 = new File(file1Path);
File file2 = new File(file2Path);
BufferedReader br1 = new BufferedReader(new FileReader(file1));
BufferedReader br2 = new BufferedReader(new FileReader(file2));
String thisLine = null;
String thatLine = null;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
while ((thisLine = br1.readLine()) != null) {
list1.add(thisLine);
}
while ((thatLine = br2.readLine()) != null) {
list2.add(thatLine);
}
br1.close();
br2.close();
return list1.equals(list2);
}
if you use java8, the code below to compare file contents
public boolean compareTwoFiles(String file1Path, String file2Path){
Path p1 = Paths.get(file1Path);
Path p1 = Paths.get(file1Path);
try{
List<String> listF1 = Files.readAllLines(p1);
List<String> listF2 = Files.readAllLines(p2);
return listF1.containsAll(listF2);
}catch(IOException ie) {
ie.getMessage();
}
}
public static String[] words = null;
public static String readFile(String name) {
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(name));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
words = everything.split("\\n");//not sure if this is right...
} finally {
br.close();
}
} catch (Exception e) {
e.getMessage();
}
return "Loaded " + i + " words";
}
I'm basically trying to read a file with data on each line. On each line in the file I'm trying to insert into the array. May someone help me figure out what I'm doing wrong here?
The problem is that:
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
sb is never actually appended anything, it is just appending empty strings over and over again.
should be:
while (line != null) {
i++;
sb.append(line);
sb.append("\n");
line = br.readLine();
}
I want to optimize this code:
InputStream is = rp.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String text = "";
String aux = "";
while ((aux = reader.readLine()) != null) {
text += aux;
}
The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above.
I need to spend as little time as possible.
Thank you
Using string concatenation in a loop is the classic performance killer (because Strings are immutable, the entire, increasingly large String is copied for each concatenation). Do this instead:
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();
You can try Apache IOUtils.toString. This is what they do:
StringWriter sw = new StringWriter();
char[] buffer = new char[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
sw.write(buffer, 0, n);
}
String text = sw.toString();
When BufferedReader reads from Socket, it is necessary to add bufferedReader.ready():
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb= new StringBuilder();
String line = "";
while (br.ready() && (line = br.readLine()) != null) {
sb.append(line + "\r\n");
}
String result = sb.toString();
One line solution:
String result = reader.lines().collect(joining(lineSeparator()));
Imports:
import java.io.*;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
I wrote a simple function to do this using StringBuilder and While loop with catching IOException inside.
public String getString(BufferedReader bufferedReader) {
StringBuilder stringBuilder = new StringBuilder();
String line = null;
do {
try {
if ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
} while (line != null);
return stringBuilder.toString();
}
You can use StringBuffer
while ((aux = reader.readLine()) != null) {
stringBuffer.append(aux);
}