JAVA Reading from file word by word using BufferedReader - java

I have to read from a file Author|Name|Year I need to store this information into class nodes. I must use BufferedReader and FileReader.
public class Book {
String author, name;
int years;
}
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception{
Book book1 = new Book();
FileReader file = new FileReader("C:/Users/ZatoIndustries/Desktop/failas.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
}
}
Input looks like:
A|bbbb|2002
B|cccc|2001
A|dddd|2000

After you read line by line:
String line = reader.readLine();
split each line by |:
String[] words = line.split("\\|");
you can then assign each of these to a descriptive variable, if you'd like:
String year = words[2]
This is the easiest way to do this, though you could have a look at Scanner for something more complicated.

I think you should use Scanner Class with next() Method ,this will be easier .

Related

Java - splitting files by newline

How can I split file by newline? I've attempted to split by doing line.split("\\r?\\n") - but when I try printing the 0th index I get the entire file content when I was expecting just the first line. but if I try printing the result at index 0 I get the entire file content, when I expected to get just the first line.
FileInputStream file = new FileInputStream("file.rcp");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while (line != null) {
String [] split = line.split("\\r?\\n");
String name = split[0]; // test to see if name will print the first line only
System.out.println(name);
line = reader.readLine();
}
File format
Food name - gyros
author - some name
Cusine type - greek
Directions - some directions
Ingredients - some ingredients
The documentation, i.e. the javadoc of readline(), says:
Returns a String containing the contents of the line, not including any line-termination characters
Which means that line.split("\\r?\\n") is the same as new String[] { line }, i.e. it's an entirely useless thing to do.
If you want to read the entire file into memory as an array of lines, just call Files.readAllLines():
List<String> linesList = Files.readAllLines(Paths.get("file.rcp"));
String[] linesArray = linesList.toArray(new String[0]);
You do not need to split any string at all. You can simply read a line and add it to a List<String> (or an array if the number of lines is known).
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream("file.rcp");
List<String> list = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(file))) {
String line = reader.readLine();
while (line != null) {
list.add(line);
line = reader.readLine();
}
}
System.out.println(list);
// An array out of the list
String[] arr = list.toArray(new String[0]);
System.out.println(Arrays.toString(arr));
}
}
Output:
[Food name - gyros, author - some name, Cusine type - greek, Directions - some directions, Ingredients - some ingredients]
[Food name - gyros, author - some name, Cusine type - greek, Directions - some directions, Ingredients - some ingredients]
If you have already read the content of your file into some string (e.g. String fileContent as shown below), you can simply split the string on \r?\n which will produce a String[].
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
String fileContent = new String(Files.readAllBytes(Paths.get("file.rcp")));
// Java11 onwards
// String fileContent = Files.readString(Path.of("file.rcp"));
String[] arr = fileContent.split("\\r?\\n");
System.out.println(Arrays.toString(arr));
}
}
Output:
[Food name - gyros, author - some name, Cusine type - greek, Directions - some directions, Ingredients - some ingredients]

Reading from a text file with a static constant declared

I'm trying to write a code that will read the contents of a file and I'm able to read it successfully. What I'm also trying to do is maybe declare a static constant like max_number_of_players so that the data read does not exceed this. Is there a way that I can do this? My code so far:
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws IOException
{
String fileName = "Data/players.txt";
File file = new File(fileName);
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
in.close();
}
}
Just add another condition to the while-loop:
int playerCount = 0;
while(in.hasNextLine() && playerCount++ < max_number_of_players){
...

Adding data from .txt document to array

Below is what the text document looks like. The first line is the number of elements that I want the array to contain. The second is the ID for the product, separated by # and the third line is the total price of the products once again separated by #
10
PA/1234#PV/5732#Au/9271#DT/9489#HY/7195#ZR/7413#bT/4674#LR/4992#Xk/8536#kD/9767#
153#25#172#95#235#159#725#629#112#559#
I want to use the following method to pass inputFile to the readProductDataFile method:
public static Product[] readProductDataFile(File inputFile){
// Code here
}
I want to create an array of size 10, or maybe an arrayList. Preferably to be a concatenation of Customer ID and the price, such as Array[1] = PA/1234_153
There you go the full class, does exactly what you want:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader inputFile = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = inputFile.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = inputFile.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = inputFile.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
}
}
OUTPUT:
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
The trick in what I am doing is using a BufferedReader to read the file, readLine to read each of the three lines, split("#"); to split each token using the # as the delimiter and create the arrays, and combinedArray[i]=strArray[i]+"_"+dataArray[i]; to put the elements in a combined array as you want...!
public static Product[] readProductDataFile(File inputFile){
BufferedReader inputFile = new BufferedReader(new FileReader(inputFile));
// the rest of my previous code goes here
EDIT: Everything together with calling a separate method from inside the main, with the file as an input argument!
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
File myFile = new File("test.txt");
readProductDataFile(myFile);
}
public static String[] readProductDataFile(File inputFile) throws FileNotFoundException, IOException{
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = myReader.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = myReader.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = myReader.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
return combinedArray;
}
}
OUTPUT
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
You don't even need the first line. Just read the second line directly into a single string and then split it by using String,split() method.
Read more for split method here.
You could use something like this (Be aware that i can't test it at the moment)
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("fileeditor.txt"));
String read = null;
String firstLine=in.readLine();
//reads the first line
while ((read = in.readLine()) != null) {
// reads all the other lines
read = in.readLine();
String[] splited = read.split("#");
//split the readed row with the "#" character
for (String part : splited) {
System.out.println(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
//close file
in.close();
} catch (Exception e) {
}
}
This is how you can do it using Java (don't forget to import):
public static Product[] readProductDataFile(File inputFile){
Scanner s = new Scanner(inputFile);
String data = "";
while(s.hasNext())
data += s.nextLine();
String[] dataArray = data.split("#");
}
You can try this way ..
Reading line by line and storing each row in a array.
Use while storing so it will split and save .
String[] strArray = secondLine.split("#");
Now use the for loop and concat the values as u wish and save ina third array .
For(int i=0 ;i< file.readline;i++)
{
string s = a[customerid];
s.concat(a[productid]);
a[k] =s;
}

Simultaneous searching of multiple words in an external file(Java)

The program that I am trying to create is a program that takes words from a user defined file, saves those words as variables and then searches a different user defined file for those words, outputting there location.
The program works up to and including the point where the program takes the words and saves them as variables. The problem with the program is that the search method returns a null result. My main suspicions are that the code in the search method is incompatible with the code in the read method, or that the 2 methods aren't running simultaneously.
The search method is in the searching class and the read method is in the reading class.
Here is my code (Containing all 3 of my classes), please excuse all of the imports.
This is the first class:
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Combination{
public static void main(String[] args) throws FileNotFoundException{
Scanner userInput = new Scanner(System.in);
Reading ReadingObject = new Reading();
System.out.println("Please enter the file that you wish to open");
String temp = userInput.nextLine();
ReadingObject.setFileName(temp);
ReadingObject.read();
Scanner searchForWord = new Scanner(System.in);
Searching SearchingObject = new Searching();
System.out.println("Please enter the file that you would like to search for these words in");
String temp1 = searchForWord.nextLine();
SearchingObject.setFileName(temp1);
SearchingObject.search();
}
}
This is the second class:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class Reading {
private String file;
public void setFileName(String fileName){
file = fileName;
}
public String getFileName(){
return file;
}
public void read(){
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
//Read the file line by line
while((strLine = br.readLine()) != null){
// \\s+ means any number of whitespaces between tokens
String [] tokens = strLine.split("\\s+");
String [] words = tokens;
for(String word : words){
System.out.print(word);
System.out.print(" ");
Searching SearchingObject = new Searching();
SearchingObject.setWord(word);
}
System.out.print("\n");
}
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
This is the third class:
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Searching {
private String file1;
public void setFileName(String fileName){
file1 = fileName;
}
public String getFileName(){
return file1;
}
private String word1;
public void setWord(String wordName){
word1 = wordName;
}
public String getWord(){
return word1;
}
public void search() throws FileNotFoundException{
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
while((strLine = br.readLine()) != null){
Pattern p = Pattern.compile(getWord());
Matcher m = p.matcher(strLine);
int start = 0;
while (m.find(start)) {
System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
start = m.end();
}
}
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any help will be greatly appreciated.
Regards
Your code is hard to read. Your reading class does not only read; it also searches. You should call it something that reflects its intended use. However, it forgets to tell its searching object where to search, and does not pass the reference to this object to anyone else. In this snippet
for (String word : words) {
System.out.print(word);
System.out.print(" ");
searching searchingObject = new searching();
searchingObject.setWord(word);
}
you are essentially not doing anything. The reference to searchingObject is lost forever.
Your reading class should keep an ArrayList of words to be searched for in the searching, instead of instancing searching objects.
Your searching class should take, as a constructor parameter, one of these ArrayLists -- and convert it into a single regex, which is much more efficient than reading the file once per word to search for. You can search for "a", "b" and "c" using the single regular expression "a|b|c". Works with longer words, too. Escape them first to avoid problems.
Oh, and please, please follow naming guidelines. Call your reading a TokenReader, and your searching a WordListSearcher...

Is there a simple way to preserve trailing tabs in java during file in?

BufferedReader and Scanner's nextLine() seem to be helping a little too much by removing all trailing whitespace. I need to preserve columns, which at the moment are allowed to be empty values, but hesitate to loop through each row using next() or getBytes() identifying tab characters since there could potentially be millions of rows with hundreds of columns.
Are there alternatives to these two methods that I'm missing for reading lines?
Are there flags or any other options to set in these methods to preserve whitespace?
Do I simply force the user to use none-blank fields?
I'm not alone in trying to preserve whitespace am I?
I have a problem with it when it's reading from a file. I have this code
import java.lang.*;
import java.util.*;
import java.io.*;
public class stringTest
{
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("wtf.txt"));
String l = br.readLine();
while (l != null) {
System.out.println(l.split("\t").length);
l = br.readLine();
}
}
}
wtf.txt contains
h\tu\tr\tf\n
o\tm\tg\t\t\n
And the output is
4
3
Additionally, if I add a line anywhere that is all tabs, ie
h\tu\tr\tf\n
\t\t\t\t\t\n
o\tm\tg\t\t\n
The output is
4
0
3
I don't think it's an issue with split because if I use the code
String s = "w\tt\tf\t\t\n";
System.out.println(""+s.split("\t").length);
String s1 = "w\tt\tf\tx\n";
System.out.println(""+s1.split("\t").length);
String s2 = "\t\t\t\t\t\t\n";
System.out.println(""+s2.split("\t").length);
The output is
5
4
6
BufferedReader.readLine() does preserve whitespace.
EDIT: It sounds like your problem is to do with split, not BufferedReader or Scanner. You can take those out of the equation very easily:
public class Test {
public static void main(String[] args) {
String line = "\t\t\t";
System.out.println(line.split("\t").length); // Prints 0
}
}
There are various different ways of splitting a string on delimiters - you might want to look at the Splitter class in Guava:
import java.util.List;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
public class Test {
public static void main(String[] args) {
Splitter splitter = Splitter.on('\t');
String line = "\t\t\t";
List<String> bits = Lists.newArrayList(splitter.split(line));
System.out.println(bits.size()); // Prints 4
}
}
BufferedReader.readLine() doesn't remove trailing tabs, certainly. Sample code:
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
// Not closing anything just for convenience
String text = "a\tb\t\r\nc\td\t";
BufferedReader reader = new BufferedReader(new StringReader(text));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line.replace("\t", "<tab>"));
}
}
}
Output:
a<tab>b<tab>
c<tab>d<tab>
Ditto Scanner.nextLine():
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws IOException {
// Not closing anything just for convenience
String text = "a\tb\t\r\nc\td\t";
Scanner scanner = new Scanner(new StringReader(text));
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println(line.replace("\t", "<tab>"));
}
}
}
(Same output.)
So whatever's stripping your whitespace, it isn't Scanner.nextLine() or BufferedReader.readLine().

Categories