using BufferedReader in Java - java
How can I use BufferedReader for reading all lines between two concrete line. for example i want to start reading from line1 то line2, can I use this code
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line1 = "StartLine";
String line2 = "EndLine";
while (!line1.equals(line2))
{
// do something
line1 = reader.readLine();
}
I write something like this, but it does not working! Please help me, I am beginner in Java!
Change the loop in following way. You need to read the line in condition and check if it's not nutll i.e. end of file.
String line1 = "StartLine";
String line2 = "EndLine";
String line3 = null;
//Iterate upto line1
while( (line3 = reader.readLine()) != null && ! line3.equals(line1));
//Print the lines till line2
while(line3 != null && ! line3.equals(line2) ) {
System.out.println(line3);
line3 = reader.readLine();
}
First you need another loop to read all lines BEFORE your "StartLine"
and then you will need to be more specific about what is NOT working.
What you expect to happen and what is not happening
You can try using BufferReader's mark and reset methods:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line1 = "StartLine";
String line2 = "EndLine";
String line;
while ((line = reader.readLine()) != null) {
if (line1.equals(line)) {
System.out.println(line);
reader.mark(100);
}
}
reader.reset();
while ((line = reader.readLine()) != null) {
if (line2.equals(line)) {
break;
} else {
System.out.println(line); //or whatever you want to do
}
}
}
You might have to play with the mark value, but something like this might work for you.
Hope that helps.
Related
Is this a good way of reading from a text file?
I've been looking around on the Internet trying to figure out which could be the best way to read from text files which are not very long (the use case here involves small OpenGL shaders). I ended up with this: private static String load(final String path) { String text = null; try { final FileReader fileReader = new FileReader(path); fileReader.read(CharBuffer.wrap(text)); // ... } catch(IOException e) { e.printStackTrace(); } return text; } In which cases could this chunk of code result in inefficiencies? Is that CharBuffer.wrap(text) a good thing?
If you want to read the file line by line: BufferedReader br = new BufferedReader(new FileReader(path)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } finally { br.close(); } If you want to read the complete file in one go: String text=new String(Files.readAllBytes(...)) or Files.readAllLines(...)
I would usually just roll like this. The CharBuffer.wrap(text) thing seems to only get you a single character ... File Reader docs BufferedReader br = new BufferedReader(fr); StringBuilder sb = new StringBuilder(); String s; while((s = br.readLine()) != null) { sb.append(s); } fr.close(); return sb.toString();
BufferedReader skip lines assets file java android
I'm trying to read a .txt-file that's located in my assets folder in an Android project. Search the file, read the file with the InputStreamer and the BufferedReader works just fine, but the problem is: it doesn't read ALL the lines. So when I want to add a line to an ArrayList for further use, not all the lines are present in this list. This is my code: InputStream inputStream; BufferedReader br; try { inputStream = getResources().getAssets().open("KeyMapping.txt"); br = new BufferedReader(new InputStreamReader(inputStream)); final ArrayList<String> viewList = new ArrayList<String>(); String line = null; //Add every line (except the first) to an arrayList while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char") { viewList.add(line); } br.close(); } catch (IOException e) { e.printStackTrace(); } The format of my .txt-file is like this: 1,2,3,4,5,6,7,8/char 1,,,,1,,,/a 2,,,,1,,,/b 3,,,,1,,,/c ,1,,,1,,,/d ,2,,,1,,,/e ,3,,,1,,,/f ,,1,,1,,,/g ,,2,,1,,,/h ,,3,,1,,,/i ,,,,1,,,1/j ,,,,1,,,2/k ,,,,1,,,3/l 1,,,,2,,,/m 2,,,,2,,,/n 3,,,,2,,,/o ,1,,,2,,,/p ,2,,,2,,,/q ,3,,,2,,,/r ,,1,,2,,,/s ,,2,,2,,,/t ,,3,,2,,,/u ,,,,2,,,1/v ,,,,2,,,2/w ,,,,2,,,3/x ... Only a few of these lines will be added to the ArrayList, does anyone know why?
while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char") This line reads 2 lines from the stream, and processes the 2nd line always. Also, you cannot compare strings with != operator. Use String.equals() method. while ((line = br.readLine()) != null) { if(line.equals("1,2,3,4,5,6,7,8,char")) continue; //add if it's not that string viewList.add(line); }
Java - Only read first line of a file
I only want to read the first line of a text file and put that first line in a string array. This is what I have but its reading the whole file. ex text in myTextFile: Header1,Header2,Header3,Header4,Header5 1,2,3,4,5 6,7,8,9,10 String line= System.getProperty("line.separator"); String strArray[] = new String[5]; String text = null; BufferedReader brTest = new BufferedReader(new FileReader(myTextFile)); text = brTest .readLine(); while (text != line) { System.out.println("text = " + text ); strArray= text.split(","); }
use BufferedReader.readLine() to get the first line. BufferedReader brTest = new BufferedReader(new FileReader(myTextFile)); text = brTest .readLine(); System.out.println("Firstline is : " + text);
If I understand you, then String text = brTest.readLine(); // Stop. text is the first line. System.out.println(text); String[] strArray = text.split(","); System.out.println(Arrays.toString(strArray));
With Java 8 and java.nio you can also do the following: String myTextFile = "path/to/your/file.txt"; Path myPath = Paths.get(myTextFile); String[] strArray = Files.lines(myPath) .map(s -> s.split(",")) .findFirst() .get(); If TAsks assumption is correct, you can realize that with an additional .filter(s -> !s.equals(""))
Also, beside of all other solutions presented here, you could use guava utility class (Files), like below: import com.google.common.io.Files; //... String firstLine = Files.asCharSource(myTextFile).readFirstLine();
I think you are trying to get one line only if it's not empty. You can use while ((text=brTest .readLine())!=null){ if(!text.equals("")){//Ommit Empty lines System.out.println("text = " + text ); strArray= text.split(","); System.out.println(Arrays.toString(strArray)); break; } }
Use this BuffereedReader reader = new BufferedReader(new FileReader(textFile)); StringBuilder builder = new StringBuilder(); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); break; } if(sb.toString.trim().length!=0) System.out.println("first line"+sb.toString);
I hope this will help someone to read the first line: public static String getFirstLine() throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); String line = br.readLine(); br.close(); return line; } to read the whole text: public static String getText() throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line).append("\n"); line = br.readLine(); } String fileAsString = sb.toString(); br.close(); return fileAsString; }
You need to change the condition of your loop String[] nextLine; while((nextLine = brTest.readLine()) != null) { ... } ReadLine reads each line from beginning up to the occurrence of \r andor \n You can also use tokenizer to split the string String[] test = "this is a test".split("\\s"); In addition it seems the file is of type CSV if it is please mention that in the question.
BufferedReader() returning empty string when there are more strings in the file?
My txt file looks like this: data;data2;data3;data4..........up till data3146 When I open the txt file in notepad I see it in the form given above. But when I copy paste the first few lines to another place, There is a 1 line gap b/w data1 and everything else. Because of this I am getting problems while accessing the file in Java and using the data with a bufferedreader in a loop. How can I correct this? I can't remove the empty line as it is not even visible in the original file.
You can ignore the blank line(s). Something like this - while ((line = reader.readLine()) != null) { if(line.trim().isEmpty()) { continue; } ...
you can try this way: BufferedReader reader = new BufferedReader(new FileReader(new File("your file path"))); String str = null; while((str = reader.readLine())!=null) { if (str.matches("[' ']+")) { continue; } else { // to do } }
I believe that the problem is in the line endings. Basically you can skip the empty lines: String line; while ((line = reader.readLine()) != null) { if ("".equals(line.trim()) { continue; } // do your stuff here }
How to escape a line that starts with a special character while reading files in java
Suppose a file contains the following lines: #Do #not #use #these #lines. Use these. My aim is to read only those lines which does not start with #. How this can be optimally done in Java?
Let's assume that you want to accumulate the lines (of course you can do everything with each line). String filePath = "somePath\\lines.txt"; // Lines accumulator. ArrayList<String> filteredLines = new ArrayList<String>(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filePath)); String line; while ((line = bufferedReader.readLine()) != null) { // Line filtering. Please note that empty lines // will match this criteria! if (!line.startsWith("#")) { filteredLines.add(line); } } } finally { if (bufferedReader != null) bufferedReader.close(); } Using Java 7 try-with-resources statement: String filePath = "somePath\\lines.txt"; ArrayList<String> filteredLines = new ArrayList<String>(); try (Reader reader = new FileReader(filePath); BufferedReader bufferedReader = new BufferedReader(reader)) { String line; while ((line = bufferedReader.readLine()) != null) { if (!line.startsWith("#")) filteredLines.add(line); } }
Use the String.startsWith() method. in your case you would use if(!myString.startsWith("#")) { //some code here }
BufferedReader.readLine() return a String. you could check if that line starts with # using string.startsWith() FileReader reader = new FileReader("file1.txt"); BufferedReader br = new BufferedReader(reader); String line=""; while((line=br.readLine())!=null){ if(!line.startsWith("#")){ System.out.println(line); } } }