I just wanted to know if there is any restriction on the number of lines readLine method can read from a file in java.Any help will be grately appreciated.This is what I am talking about:
FileReader fr1=new FileReader("/homes/output_train_2000.txt");
BufferedReader br1=new BufferedReader(fr1);
while((line1=br1.readLine())!=null){ }
Thanks.
When buffered reader is used, the entire file is never read into memory, so it should be able to handle files of any size that your operating system supports for.
It can read any number of lines .
Are you trying to restrict the number of lines read? If so then you can easily add some code to do that:
FileReader fr1=new FileReader("/homes/output_train_2000.txt");
BufferedReader br1=new BufferedReader(fr1);
int numLinesRead = 0;
int maxLines = 1000;
while((numLinesRead < maxLines) && (line1=br1.readLine())!=null){
numLinesRead++;
// other stuff
}
No restriction that I know of. Here's a better way of doing it:
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader( "/homes/output_train_2000.txt") );
String line = null;
do {
line = reader.readLine();
if( line != null ) {
// Do something
}
} while( line != null );
} catch (Exception e) {
e.printStackTrace();
} finally {
if( reader != null )
try {
reader.close();
} catch (IOException e) {
}
Related
So I have this method here that should return the amount of lines in a csv file. Pretty simple right? Thing is instead of returning the amount of lines in the csv file(in this case 15) it returns 66. I honestly have know Idea why this would happen. I checked the csv file and verified that it is indeed 15 lines long with no empty lines. Also does anyone know why my Jpanes wont display without those three lines commented lines, my ide says the variables aren't in use anywhere.
public static int getLineCount(){
int line=0;
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data =inputStream.next();//this line is useless but the program doesn't display with out it
String[] values = data.split(",");//this line is useless but the program doesn't display with out it
i++;//this line is useless but the program doesn't display with out it
line++;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
return line;
}
Use BufferedReader instead of Scanner:
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
while(reader.readLine() != null){
line++;
}
public static int getLineCount(){
String csvFilePath = "C:\\Users\\uzochi\\desktop\\txt.csv";
String line = "";
int numberOfLines=0;
try {
BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
while (( line = br.readLine()) != null) {
numberOfLines++;
}
}catch(FileNotFoundException e){
//
}catch (IOException ex) {
//
}
return numberOfLines;
}
What i want is to reduce exceptions to be thrown from a method.
As you can see i have an inner try catch in the outer catch block to avoid the exception be thrown.
Is this the normal way to do this or are there better (more elegant) ways?
Or is this approach completely false and i should just throw the exception?
public static String readText(String filename) {
String text = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line = null;
while( (line = br.readLine()) != null ){
text += line;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return text;
}
Personally I'd go for a more modern approach with either Files.readAllLines(); or Files.lines();.
Then all you need to handle is an IOException and the resources are cleaned up for you automatically.
There are several ways to be more concise in what you want to do:
Use a Java 7 feature to catch multiple exceptions in one catch:
try {...} catch(FileNotFoundException | IOException e) {...}
Use a Java 7 feature called try-with-resources so you can ommit the finally:
try (BufferedReader br =
new BufferedReader(new FileReader(filename))) {
}
In regards to throwing the exceptions or not is a design choice:
Do I want to signal errors to the upper layer?
Can I handle the error on the upper level?
If you are using Java 7 or later you can use try with resource.
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
String line = null;
while( (line = br.readLine()) != null ){
text += line;
}
}
I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer
So I'm having an issue reading a text file into my program. Here is the code:
try {
InputStream fis = new FileInputStream(targetsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//while(br.readLine()!=null){
for (int i = 0; i < 100; i++) {
String[] words = br.readLine().split(" ");
int targetX = Integer.parseInt(words[0]);
int targetY = Integer.parseInt(words[1]);
int targetW = Integer.parseInt(words[2]);
int targetH = Integer.parseInt(words[3]);
int targetHits = Integer.parseInt(words[4]);
Target a = new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
} catch (Exception e) {
System.err.println("Error: Target File Cannot Be Read");
}
The file I am reading from is 100 lines of arguments. If I use a for loop it works perfectly. If I use the while statement (the one commented out above the for loop) it stops at 50. There is a possibility that a user can run the program with a file that has any number of lines, so my current for loop implementation won't work.
Why does the line while(br.readLine()!=null) stop at 50? I checked the text file and there is nothing that would hang it up.
I don't get any errors from the try-catch when I use the while loop so I am stumped. Anyone have any ideas?
also very comprehensive...
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.
You can use a structure like the following:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
In case if you are still stumbling over this question.
Nowadays things look nicer with Java 8:
try {
Files.lines(Paths.get(targetsFile)).forEach(
s -> {
System.out.println(s);
// do more stuff with s
}
);
} catch (IOException exc) {
exc.printStackTrace();
}
Thank you to SLaks and jpm for their help. It was a pretty simple error that I simply did not see.
As SLaks pointed out, br.readLine() was being called twice each loop which made the program only get half of the values. Here is the fixed code:
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String words[]=new String[5];
String line=null;
while((line=br.readLine())!=null){
words=line.split(" ");
int targetX=Integer.parseInt(words[0]);
int targetY=Integer.parseInt(words[1]);
int targetW=Integer.parseInt(words[2]);
int targetH=Integer.parseInt(words[3]);
int targetHits=Integer.parseInt(words[4]);
Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
Thanks again! You guys are great!
Concept Solution:br.read() returns particular character's int value so loop
continue's until we won't get -1 as int value and Hence up to there it prints
br.readLine() which returns a line into String form.
//Way 1:
while(br.read()!=-1)
{
//continues loop until we won't get int value as a -1
System.out.println(br.readLine());
}
//Way 2:
while((line=br.readLine())!=null)
{
System.out.println(line);
}
//Way 3:
for(String line=br.readLine();line!=null;line=br.readLine())
{
System.out.println(line);
}
Way 4:
It's an advance way to read file using collection and arrays concept
How we iterate using for each loop.
check it here
http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html
In addition to the answer given by #ramin, if you already have BufferedReader or InputStream, it's possible to iterate through lines like this:
reader.lines().forEach(line -> {
//...
});
or if you need to process it with given order:
reader.lines().forEachOrdered(line -> {
//...
});
why doesn´t if (txtLine == null) { break; };work? or maybe the correct answer is why does it still set the string txtLine to null (literally). The way I understand it, it should break the moment the string is null? I don´t want it to set the string to "null". but stop when there are no more lines in the *.txt file
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
if(txtLine == null){
break;
};
txtLine = txtReader.readLine();
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
the txtFile variable is defined as an IVAR
private int nChars = 0;
private String txtLine = new String();
private ArrayList <String> array = new ArrayList <String>();
I think the ordering of when you break and when you change the value of txtLine to be the next line read from the file is backwards, your code should look something like:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
txtLine = txtReader.readLine();
// check after we read the value of txtLine
if(txtLine == null){
break;
}
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
But this is a much more concise (and I think, clearer) form:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while ((txtLine = txtReader.readLine()) != null) {
// Reads one line.
println(txtLine);
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
Where while ((txtLine = txtReader.readLine()) != null) sets txtLine to the next line, and then checks that txtLine is not null before continuing.