Read a text file line by line into strings - java

How do I read the contents of a text file line by line into String without using a BufferedReader?
For example, I have a text file that looks like this inside:
Purlplemonkeys
greenGorilla
I would want to create two strings, then use something like this
File file = new File(System.getProperty("user.dir") + "\Textfile.txt");
String str = new String(file.nextLine());
String str2 = new String(file.nextLine());
That way it assigns str the value of "Purlplemonkeys", and str2 the value of "greenGorilla".

You can read text file to list:
List<String> lst = Files.readAllLines(Paths.get("C:\\test.txt"));
and then access each line as you want
P.S. Files - java.nio.file.Files

You should use an ArrayList.
File file = new File(fileName);
Scanner input = new Scanner(file);
List<String> list = new ArrayList<String>();
while (input.hasNextLine()) {
list.add(input.nextLine());
}
Then you can access to one specific element of your list from its index as next:
System.out.println(list.get(0));
which will give you the first line (ie: Purlplemonkeys)

If you use Java 7 or later
List<String> lines = Files.readAllLines(new File(fileName).toPath());
for(String line : lines){
// Do whatever you want
System.out.println(line);
}

Sinse JDK 7 is quite easy to read a file into lines:
List<String> lines = Files.readAllLines(new File("text.txt").toPath())
String p1 = lines.get(0);
String p2 = lines.get(1);

How about using commons-io:
List<String> lines = org.apache.commons.io.IOUtils.readLines(new FileReader(file));
//Direct access if enough lines read
if(lines.size() > 2) {
String line1 = lines.get(0);
String line2 = lines.get(1);
}
//Iterate over all lines
for(String line : lines) {
//Do something with lines
}
//Using Lambdas
list.forEach(line -> {
//Do something with line
});

You can use apache.commons.io.LineIterator
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}
One can also validate line by overriding boolean isValidLine(String line) method.
refer doc

File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
System.out.println(input.nextLine());
}

Related

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;
}
}
}

Read text from file line by line to 2 strings variables

I have a file with some words saved in a text file like that:
Koraa
Orakaa
Balaes
Ealaaab
Araqko
I need to know how to read it using Java like below:
string firstWord = "Koraa";
and the 2nd line in another string
string secondWord = "Orakaa";
then I will do some stuff on those 2 strings then secondWord & firstWord contents' will be replaced with next 2 lines in the same file !
for example:
firstWord = "Balaes";
secondWord = "Ealaaab";
... etc the operation will be looping on all these words.
You can have an ArrayList of String and read separate lines from a file using Scanner.
List<String> al = new ArrayList<String>();
File file = new File("example.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
al.add(scanner.nextLine())
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
You can refer to the individual words, in order, with al.get(int index).

Read file from txt and split string using comma

Why is it it says that there is no split method found ? I want to split one lines to several parts. But there is error. Why is that so ?
try {
Scanner a = new Scanner (new FileInputStream ("product.txt"));
while (a.hasNext()){
System.out.println(a.nextLine()); //this works correctly, all the lines are displayed
String[] temp = a.split(",");
}
a.close();
}catch (FileNotFoundException e){
System.out.println("File not found");
}
split() is not defined for Scanner but for String.
Here's a quick fix:
String line = a.nextLine();
System.out.println(line); //this works correctly, all the lines are displayed
String[] temp = line.split(",");
split method works on the String and not on the Scanner. So store the contents of
a.nextLine()
in a string like this
String line = a.nextLine();
and then use split method on this stirng
String[] temp = line.split(",");

Java Matcher: How to match multiple lines with one regex

My method takes a file, and tries to extract the text between the header ###Title### and closing ###---###. I need it to extract multiple lines and put each line into an array. But since readAllLines() converts all lines into an array, I don't know how to compare and match it.
public static ArrayList<String> getData(File f, String title) throws IOException {
ArrayList<String> input = (ArrayList<String>) Files.readAllLines(f.toPath(), StandardCharsets.US_ASCII);
ArrayList<String> output = new ArrayList<String>();
//String? readLines = somehow make it possible to match
System.out.println("Checking entry.");
Pattern p = Pattern.compile("###" + title + "###(.*)###---###", Pattern.DOTALL);
Matcher m = p.matcher(readLines);
if (m.matches()) {
m.matches();
String matched = m.group(1);
System.out.println("Contents: " + matched);
String[] array = matched.split("\n");
ArrayList<String> array2 = new ArrayList<String>();
for (String j:array) {
array2.add(j);
}
output = array2;
} else {
System.out.println("No matches.");
}
return output;
}
Here is my file, and I'm 100% sure that the compiler is reading the correct one.
###Test File###
Entry 1
Entry 2
Data 1
Data 2
Test 1
Test 2
###---###
The output says "No matches." instead of the entries.
You don't need regex for that. It's enough to loop through the array and compare items line by line, taking those between the start and end tags.
ArrayList<String> input = (ArrayList<String>) Files.readAllLines(f.toPath(), StandardCharsets.US_ASCII);
ArrayList<String> output = new ArrayList<String>();
boolean matched = false;
for (String line : input) {
if (line.equals("###---###") && matched) matched = false; //needed parentheses
if (matched) output.add(line);
if (line.equals("###Test File###") && !matched) matched = true;
}
As per your comment, if they are going to be in the same way as posted, then i don't think regex is needed for this requirement. You can read line by line and do a contains of '###'
public static void main(String args[])
{
ArrayList<String> dataList = new ArrayList<String>();
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// this line will skip the header and footer with '###'
if(!strLine.contains("###");
dataList.add(strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
//Now dataList has all the data between ###Test File### and ###---###
}
You can also change the contains method parameter according to your requirement to ignore lines!

Java Scanner multiple delimiter

I know this is a very asked question but I can't find and apropiate answer for my problem. Thing is I have to program and aplication that reads from a .TXT file like this
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
My question is how what can I do to tell Java that I want String before : in one ArrayList and Strings after : in another ArrayList?? I guess It's using delimeter method but I don't know how use it in this case.
Sorry for my poor english, I've to improve It i guess. Thanks
use split function of java.
steps:
Declare two arrayList. l1 and l2;
read each line.
split each line by ":", this will return a array of length 2, array. (as per your input)
l1.add(array[0]) , l2.add(array1)
try yourself, post code if you need help :)
check here for use of split function, though through google you can find many different example
Split the string using ":" as delimiter. Add the odd entries from the result to one list and even to another list.
If your text is like this:
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
You can achieve what you want by using:
StringBuilder text = new StringBuilder();
Scanner scanner = new Scanner(new FileInputStream(fFileName), encoding); //try utf8 or utf-8 for 'encoding'
try {
while (scanner.hasNextLine()){
String line = scanner.nextLine();
String before = line.split(":")[0];
String after = line.split(":")[1];
//dsw 'before' and 'after' - add them to lists.
}
}
finally{
scanner.close();
}
Scanner scanner = new Scanner(new FileInputStream("YOUR_FILE_PATH"));
List<String> firstList = new ArrayList<String>();
List<String> secondList = new ArrayList<String>();
while(scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
String[] tokenizedString = currentLine.split(":");
firstList.add(tokenizedString[0]);
secondList.add(tokenizedString[1]);
}
scanner.close();
Enumerating firstList and secondList will get you the desired result.
1. Use ":" as delimiter.
2. Then Store them in the String[] using split() function.
3. Try using BufferedReader instead of Scanner.
Eg:
File f = new File("d:\\Mytext.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
ArrayList<String> s1 = new ArrayList<String>();
ArrayList<String> s2 = new ArrayList<String>();
while ((br.readLine())!=null){
String line = br.readLine();
String bf = line.split(":")[0];
String af = line.split(":")[1];
s1.add(bf);
s2.add(af);
}

Categories

Resources