I have a text file that consists of several entries such as:
one
two
three
four
five
six
The text file contains 100 lines and I want to read each 5 lines in a once. I have this code but it give null values:
BufferedReader br = null;
String sCurrentLine;
int lines = 0;
try {
br = new BufferedReader(new
FileReader("/users/MoathIbrahem/Desktop/Questions.txt"));
while(br.readLine()!= null)lines++;
for(int i = 0;i < lines;i++)
System.out.println(br.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
In this line
while(br.readLine()!= null)lines++;
you are going to read ALL of the text file.
Nothing more to read unless you re-open the File or use mark/reset
This is happening because when you read a line a reader pointer advances. When you try to read in the for loop this pointer has reached the end of the document.
I recommend you to not count the lines before. Like the user gotomanners says in his answer:
String line;
while ((line = fileReader.readLine()) != null) {
System.out.println(line);
}
Related
This question already has answers here:
Modify the content of a file using Java
(6 answers)
Closed 3 years ago.
I am new at java and teacher gave us a project homework. I have to implement read the file line by line, slice the lines at the comma and store the parts at a multidimensional array, change the specific part of the line (I want to change the amount).
The given file:
product1,type,amount
product2,type,amount
product3,type,amount
product4,type,amount
product5,type,amount
I tried this code but I couldn't change the specific part.
BufferedReader reader;
int j=0;
int i=0;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
j++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
String total_length[][]=new String[j][3];
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
String[] item = line.split(",");
total_length[i][0]=item[0];
total_length[i][1]=item[0];
total_length[i][2]=item[0];
i++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Thanks a lot!
First, you need to read the file. There are plenty of way to do it, one of them is:
BufferedReader s = new BufferedReader(new FileReader("filename"));
Which allows you to do s.readLine() to read it line by line.
You can use a while loop to read it until the end. Note that readLine will return null if you reach the end of the file.
Then, for each line, you want to split them with the coma. You can use the split method of Strings:
line.split(",");
Putting it all together, and using a try-catch for IOException, you get:
List<String[]> result = new ArrayList<>();
try (BufferedReader s = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = s.readLine()) != null) {
result.add(line.split(","));
}
} catch (IOException e) {
// Handle IOExceptions here
}
If you really need a two dimensional array at the end, you can do:
String[][] array = new String[0][0];
array = result.toArray(array);
You then have read the file in the format you wanted, you can now modify the data that you parsed.
I have a program in Java that will print the contents of a text file to console.
I created the following loop to do this:
if ("1".equals(select)) {
while (true){
System.out.println(inFile.nextLine());
}
}
However I cannot edit the file itself to add a kind of character to tell me when the file end has been reached; instead the end of the file will be when I get 2 blank lines in a row, but I'm not sure how to achieve this.
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
Hope this answers
I have an assignment where i have to read a CSV file containing data with some repeated lines. How to remove the duplicate values and print only the unique values in Eclipse
The data is similar to this:-
1,Ron,1234,ABC,12
2,Harry,4125,DEF,14
3,Kent,1786,GHI,15
1,Ron,1234,ABC,12
2,Harry,4125,DEF,14
String csvFile = "csv.csv";
BufferedReader br = null;
String line = "";
HashSet<String> lines = new HashSet<>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (lines.add(line)) {
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It may help you
My suggestion is to use the following strategy:
1st step: create a HashMap http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
where you will save each line of the CSV you read. You will save in a hashmap because Hashmap will NOT accept a key that is like another. So, each line you will read, you will save in the hashmap as a KEY!
So, the logic is: Try to save the line you just read as a Key. IF it works, print that line. If it didn't work, discard the line and read the next one.
Got it?
2nd step:
Use a BufferedReader http://docs.oracle.com/javase/7/docs/api/index.html?java/io/BufferedReader.html to read line by line of the CSV.
Get each line of the CSV with the BufferedReader with readLine().
It will save the line you are reading in a String
That's it.
So, here is the overview of the entire code:
1- Read each line of the code with BufferedReader.readLine()
2- Get that string you got from readLine and try to add to your Hashmap as the Key of the hashmap: if it works, print the String. If it doesn't work, discard the string;
3- Read the next line.
Is there a way to check whether a file was correctly written, I mean if there is an EOF at the end?
I'm asking that because I have a program that takes some file, merge them in a very big file and then use it to get statistics from it.
The point is that the second part never ends because it doesn't recognize the end of file.
The relevant parts of the code are the following:
(please do not ask for the whole code as I cannot post for important reasons)
FileWriter file=null;
PrintWriter pw = null;
String pathToRead=null;
InputStreamReader isr = null;
BufferedReader br = null ;
FileInputStream fis = null ;
TestJFileChooser d=new TestJFileChooser();
int c=1;
String line=null;
....
//here i select the files
selectedFile=new File(pathToRead);
//here I get one buffer reader for each file got with listFiles()
for(File file_sel:app){
if (file_sel.getName().startsWith("gtou")){
System.out.println(file_sel.getName());
fis = null;
try {
fis = new FileInputStream(file_sel);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
isr=new InputStreamReader(fis);
br=new BufferedReader(isr);
map.put(i, br);
num_file++;
i++;
}
}
//then I select the output file and open a print writer for it
fileToWrite=new File(pathToRead);
try {
file = new FileWriter(fileToWrite);
pw= new PrintWriter(file);
} catch (IOException e1) {
e1.printStackTrace();
}
//merging part
....
line=br.readLine();
while(line!=null){
System.out.println("line is:"+line);
....
line=br.readLine();
}
//end of merging ....
pw.flush();
pw.close();
try {
if (file!=null) file.close();
fis.close();
isr.close();
br.close();
for(int fi=0;fi<num_file;fi++){
br2=map.get(fi);
br2.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
so.kill();
Runtime r=Runtime.getRuntime();
r.gc();
//this is a popup that comes out
GlitchSquad gli=new GlitchSquad("Completed");
the problem is that as output I get:
line is: null ;
line is: null ;
line is: null ;
etc
And never get to "completed" popup =(
I cannot understand what is exactly that null because the control line!=null doesn't work.
I also tried to use that null as a string ..but nothing..
I thought that was a problem in how I close the streams but now the code seems correct to me ..but still no way to stop it..
Suggestion?
Thanks in advance!
p.s. it is a summarized version in order to focus on the streams.. variables are correctly declared and the same is for imports etc
edit: code updated
EOF is EOF. There is no more data. Unless you have an expected EOF mark within the file, or a self-describing protocol that tells you where the EOF mark should be, there is no way to determine whether the file was completely written.
I don't know if it will solve your problem, but I'd be using this code instead:
try {
fis = new FileInputStream(file_sel);
isr=new InputStreamReader(fis);
br=new BufferedReader(isr);
map.put(num_file++, br);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Otherwise there may be uncaught "NullPointer"-exceptions or strange BufferedReaders in your "map". ( I don't right now know how new InputStreamReader(null) will behave.)
It looks like i and num_file have always equal values, so just drop i. Or use a LinkedList and drop both.
If there's not a special merging that you have to do, I'd just do it like this:
OutputStream os;
try {
os = new FileOuputStream(outfile);
} catch (FileNotFoundException e) {
os = null;
e.printStackTrace();
}
if (os != null) {
for(File file_sel:app) {
if (file_sel.getName().startsWith("gtou")) {
System.out.println(file_sel.getName());
InputStream is = null;
try {
is = new FileInputStream(file_sel);
byte[] buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = is.read(buffer)) > 0) {
os.write(buffer, 0, readBytes);
}
fos.flush();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
If you read files with different encodings, you will have to modify at least the reading of course.
If it doesn't work, I'd suggest you build a "summarized" and runable sample program.
The core of your question is this code:
BufferedReader br = ...
String line = br.readLine();
while (line != null) {
System.out.println("line is:" + line);
...
line = br.readLine();
}
You say that this repeatedly outputs this:
line is: null ;
line is: null ;
(Notice the " ;" on the end!!!)
The only way that can happen is if the file you are reading contains at least one line that look like this:
null ;
Indeed, unless the "..." code includes a continue statement, there must must be lots of those lines in the input file.
Is there a way to check whether a file was correctly written?
Yea. Look at it using a text editor and/or check its file size.
I mean if there is an EOF at the end?
In modern file systems, EOF is a position not a marker. Specifically it is the position after the last byte of the file. So it is logically impossible for a file to not have an EOF. (You'd have to have a file that is infinite in length for there to be no EOF.)
Here is my code:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null) {
textLine = reader.readLine();
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
And my .txt file contains the following:
contig00001 length=586 numreads=4
CGGGAAATTATCcGCGCCTTCACCGCCGCCGGTTCCACCGACGAACGGATACTGCGtGaa
ggCCGCGATCCCGTCggaCGGAAAaCGCCcTGGCCCGGGAaCATACCGTTCGGGCCGCCA
AGTGTTATAGCCGGACCACTTGTCAGAACATTTCCaaTCCGAAGATGTGAGTtCGGAAGg
TAAAAGCCCGACAAGTTGCGCGgTGAATTTACCTTtACcGCACGATATGCGTCCGTATTA
AaGAAAaGTTCGAAATTATCAGTAAGGCCGACCTGAAaGCTGACCGGGAGTTCAACAAAA
TCTGCATCACCcGGgTCACGGTCGAAATTGCTGTACGCGGCGCTGAACGTAAATTCACCC
TTTcTAAGGGTGTCGCcGTCGTAAACCGTAAaCAaGCCGGTAGCGCCGCCCATCGGGCCG
CCGGTACCAACCGTCGGTGCCGTGTTTCTtGCATCATTGTCCGATCGAGCGTTCTCGTCC
GCTTGTGCAAaTCCTGCAaTAGCTAACGTGAAAACGATCAGAGCTGTTGTAAATACTCTA
TAAGCGAGATTCATCACATTCCTCcGCCGAAATAAAAAGTTAATTt
contig00002 length=554 numreads=4
TGCGCCAaCCGCGCTCTtCATAAaTGGGCACTGCTCCCGATGGCCgACTCGGGCGGTTCG
CCATGAGATCTTTGCCtACCcAGgAaCtCACcACCAAGTCTGATTGCTGTGTGTTTtCTT
CAAGTCCCTATTTCTATTCtCTTtAATGGAACCCGTAGGAAACCCGTGTAGGACGCGGGA
aCCGCACTTgAAGGGGGAGGCGCGGGGTACCGGtCCGGGAACGTACGGGTACCGGCGGGG
gAGGGGAGGGGGACCgCTCCGGGAAGGCCAGGGGACGGATTGGGGAAGGgCGGGTACCGA
AGCGGGgAAaTGGGggAaCcGGCGAGAGGGTTCCTCGCTAAGTGGGGGAAATaGGGGAAA
GGTTGACCAGTGGTtCCCcGCTCTCGTAACATGCCTCAGATAGCGCCATCCGCTGTACCT
GGtcaggtcGctggcaacttcggccgagcaggtgaacccgaaaggtgagggtcagtgtga
cacaccaaccgaacaccgacgaggcaagcgtaggagccggcgtggccgcgcccggcggcg
ctgaggactcctcg
But shows the output by skipping the first two lines.
What is the reason for this?
You don't need the while loop, or the readLine method. Just call jtextArea1.read(reader, "jTextArea1")
Edit: update following your comment. If you want to skip all lines starting with >, you will need to read the file manually and then append each line to your textArea.
So something like:
String line;
while ((line = reader.readLine()) != null)
{
if (!line.startsWith(">"))
{
jTextArea.append(line + "\n");
}
}
Use:
FileReader reader = new FileReader("filename.txt");
txtarea.read(reader, "filename.txt"); //Object of JTextArea
You need only the above two lines to read from a file and put it into JTextArea...
The problem must have been solved by the time, yet there's still no answer to the question why the first two lines are skipped.
You create reader and then read the first two lines from the file, remaining lines are loaded into jTextArea1.
Your code:
/* 1 */ while((textLine=reader.readLine())!=null){
/* 2 */ textLine = reader.readLine();
/* 3 */ jTextArea1.read(reader,"jTextArea1");
}
Line 1 reads the first line from the file. Then in the body of while you read the second line from the file at line 2. Line 3 reads the rest of the file into jTextArea1.
On the next iteration of the while loop, reader.readLine() returns null since the file is completely read.
To load text in a JTextComponent use its read method as suggested by Phill and Bhushankumar.
The second parameter to read is not used by JTextArea, so it's safe to pass null. This second parameter is usually used to store to URL of the loaded file to resolve relative references, for example links in an HTMLDocument.
textLine = reader.readLine(); is called twice...
Fixed:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null){
// textLine = reader.readLine(); // Remove this line
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
Correctly is:
try {
FileReader fr = new FileReader("tablica.txt");
BufferedReader reader = new BufferedReader(fr);
do {
l.read(reader, null);
}
while ((textLine=reader.readLine()) != null)
;
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}