Read lines from Text file - java

I just want to read some specific lines from a text file not all the lines.
I tried the following code:
public class BufferedReaderDemo {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("Demo.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line!=null)
{
System.out.println(line);
line = br.readLine();
}
br.close();
}
}
Using this code I am able to get all the lines. But I want to print some specific 2–3 lines in console that start with "namespace" and end with "Console".
How can I achieve this?

You have no choice, if you want to know if a line contains some specific words, you have to read it.
If you want only print these lines, you can add a condition before printing them.
String line = br.readLine();
while(line!=null){
if (line.startsWith("namespace") && line.endsWith("Console")){
System.out.println(line);
}
line = br.readLine();
}

Use String.startsWith and String.endsWith:
while(line!=null)
{
if(line.startsWith("namespace") && line.endsWith("Console")) {
System.out.println(line);
}
line = br.readLine();
}

Related

How do I use Java to incrementally read line from file?

I want to use Java to read line by line from input file. The logic of the code should be:
The loadFile() in the log class reads the first line. The deltaRecords stores the first line
In the Main class, I call loadFile(), and it only upload the data in the deltaRecords, which is the 1st line. The loadFile() waits until the first line has been analyzed by testRecords() in Main class
The loadFile() in the log class reads the 2nd line. The deltaRecords stores the 2nd line
In the Main class, I call loadFile(), and it only upload the data in the deltaRecords, which is the 2nd line. The loadFile() waits until the 2nd line has been analyzed by testRecords() in Main class
The loadFile() in the log class reads the 3rd line. The deltaRecords stores the 3rd line.
For example, my input file is:
TOM 1 2 <br/>
Jason 2 3 <br/>
Tommy 1 4 <br/>
After I read TOM 1 2. I need to halt the process and do the analysis. Then I continue to read Jason 2 3.
Here is my current code. In the log class, I defined loadFile() to read the input line by line. In the Main class, I defined testRecords() to analyze.:
public void loadFile(String filename) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
Main main = new Main();
String line = br.readLine();
int count = 0;
while (line != null) {
if (line.length() == 0) {
line = br.readLine();
continue;
}
LogRecord record = new LogRecord(line);
//add record to the deltaRecord
deltaRecords.add(record);
//here I need to wait until it has been analyzed. Then I continue read
//initial the deletaRecords and add current line to the old record
existRecords.add(record);
line = br.readLine();
}
}catch(Exception e){
System.out.println("load log file failed! ");
e.printStackTrace();
}
In my main function, I call loadfile:
Log log = new Log();
log.loadFile("data/output_01.txt");
QueryEngine.queryEngine.log = log;
testRecord(log);
Could anyone tell me how to solve this problem? Thank you very much.
You don't need to read a line when you create your line variable
Replace
String line = br.readLine();
with
String line = null;
You can use value assignment inside a conditional
Replace
while (line != null) {
with
while ((line = br.readLine()) != null) {
In the case of empty lines continue
Replace
if (line.length() == 0) {
line = br.readLine();
continue;
}
with
if (line.length() == 0) {
continue;
}
How your code should look like
String line = null;
while ((line = br.readLine()) != null) {
if (line.length() == 0) continue;
//Analyze your line
}
You can solve it using a Consumer lambda function as input on your loadFile as follow:
public void loadFile(String filename, Consumer<LogRecord> lineAnalyzer) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
Main main = new Main();
String line = br.readLine();
int count = 0;
while (line != null) {
if (line.length() == 0) {
line = br.readLine();
continue;
}
LogRecord record = new LogRecord(line);
//add record to the deltaRecord
deltaRecords.add(record);
//here I need to wait until it has been analyzed. Then I continue read
//Analyze line
lineAnalyzer.accept(record);
existRecords.add(record);
line = br.readLine();
}
}catch(Exception e){
System.out.println("load log file failed! ");
e.printStackTrace();
}
Then when you call the loadFile function you can specify the analysis line logic as follow:
Log log = new Log();
QueryEngine.queryEngine.log = log;
log.loadFile("data/output_01.txt",logRecord -> {
System.out.println("Starting analysis on log record "+logRecord);
// Analyze the log record
testRecord(log);
});
You can use scanner to read the file and process line by line. I have attached snippet code below.
public void loadFile(String filename) {
try {
Scanner sc= new Scanner(new File(filename));
while (sc.hasNext()) {
String line = sc.nextLine();
LogRecord record = new LogRecord(line);
//add record to the deltaRecord
deltaRecords.add(record);
//here I need to wait until it has been analyzed. Then I continue read next line
//Place your code here
}
} catch (FileNotFoundException fe) {
System.err.println(fe);
}
}

reading input from file until specific word is read

i am writing a java program to read a file and print output to another string variable.which is working perfectly as intended using is code.
{
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
}
System.out.println(key); //this prints contents of .txt file
}
this prints whole text in the file.But i want to only print the lines till word END is encountered in file.
example: if input.txt file contains following text : this test file END extra in
it should print only :
this test file
Just do a simple indexOf to see where it is and if it exists in the line. If the instance is found one option would be using substring to cut off everything up until the index of the keyword. For a bit more control though try using java regular expressions.
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while ((line = reader.readLine()) != null && line.indexOf("Keyword to look for") == -1)
key += line;
System.out.println(key);
I am not sure why it needs to be any more complicated than this:
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = re.readLine();
if (str.equals("exit")) break;
// whatever other code.
}
You can do it in many ways. one of them is using indexOf method to specify the start index of "END" in input and then using subString method.
for more information, read documentation of String calss. HERE
This will work for your issue.
public static void main(String[] args) throws IOException {
String key = "";
FileReader file = new FileReader("/home/halil/khalil.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
} String output = "";
if(key.contains("END")) {
output = key.split("END")[0];
System.out.println(output);
}
}
You have to change your logic to check if the line contains "END".
If END not found in a line, add the line to key stringin your program
If yes, split that line into word array, read the line till you encounter the word "END" and append it to your key string. Consider using Stringbuilder for key.
while (line != null) {
line = reader.readLine();
if(!line.contains("END")){
key += line;
}else{
//Note that you can use split logic like below, or use java substring
String[] words = line.split("");
for(String s : words){
if(s.equals("END")){
return key;
}
key += s;
}
}
}

Combine a Read and Parse text.txt

Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Trouble with StringTokenizer using two lines of text

I have a program that is supposed to take a text file specified in the run arguments and print it one word at a time on separate lines. It is supposed to omit any special characters except for dashes (-) and apostrophes (').
I have basically finished the program, except that I can only get it to print the first line of text in the file.
Here is what is in the text file:
This is the first line of the input file. It has
more than one line!
Here are the run arguments I am using:
java A1 A1.txt
Here is my code:
import java.io.*;
import java.util.*;
public class A1
{
public static void main (String [] args) throws IOException
{
if (args.length > 0)
{
String file = (args[2]);
try
{
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
int i = 1;
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
br.close();
} catch (IOException e)
{
System.out.println ("The following error occurred " + e);
}
}
}
}
You are only calling readLine() once! So you are only reading and parsing through the first line of the input file. The program then ends.
What you want to do is throw that in a while loop and read every line of the file, until you reach the end, like so:
while((s = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
Basically, what this means is "while there is a next line to be read, do the following with that line".

How to handle ArrayIndexedBoundexception in Java

I have been trying to get a specific columns from a csv file say having 30 columns but i need only 3 columns entirely when i execute the following code only i get only one entire column data..how to get 3 column data at a time.when i run it prints only one column...when i try to print multiple column it shows error message like
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ReadCVS.main(ReadCVS.java:19)
public static void main(String[] args) throws Exception {
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("txt.csv"));
String line = br.readLine();
while((line = br.readLine()) !=null){
String[] b = line.split(splitBy);
PrintWriter out = new PrintWriter(new FileWriter("new.csv",true));
out.println(b[0]);
out.close();
}
br.close();
}
The problem is probably is:
You have only one line in your, txt.csv file.
When you called br.readLine(); for the first time, that line is read from the file and stored in String line variable. But you ignored that line, and you've read again, in your while condition:
while((line = br.readLine()) !=null)
So maybe you have an empty line or empty string after that first line. Then the while condition is true, but an empty String is stored in line variable. So the b[] has no element and b[0] is out of the bound.
One solution is to change this line:
String line = br.readLine();
to
String line = null;
[EDIT]
So if you try to read a file like the one in mkyong's site (as you linked in your comment) and split the lines by "," and write them in a new file for example, you can use a code like the code below:
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
BufferedReader br = new BufferedReader(new FileReader("c:\\txt.csv"));
String splitBy = ",";
String line = null;
while((line = br.readLine()) !=null){
StringBuffer newLine = new StringBuffer();
String[] b = line.split(splitBy);
for (int i = 0; i<b.length; i++)
{
if(b[i] == null || b[i].trim().isEmpty())
continue;
newLine.append(b[i].trim() + ";");
}
out.write(newLine.toString());
out.newLine();
}
out.close();
br.close();
}
Also you should know that the following line opens the output file in appendable way(the second boolean parameter in the constructor):
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
Also I assumed the contents of the source file is the same as in mkyong's site, somethimg like this:
"1.0.0.0",, , ,"1.0.0.255","16777216", , "16777471","AU" ,, "Australia"
"1.0.1.0" , ,, "1.0.3.255" ,, ,"16777472","16778239" , , "CN" , ,"China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Good Luck.

Categories

Resources