Java reading words into ArrayList of Strings [duplicate] - java

This question already has answers here:
Java reading a file into an ArrayList?
(13 answers)
Closed 6 years ago.
I would like to read in a file (game-words.txt) via a buffered reader into an ArrayList of Strings. I already set up the buffered reader to read in from game-words.txt, now I just need to figure out how to store that in an ArrayList. Thanks ahead for any help and patience!
Here is what I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOExecption;
class Dictionary{
String [] words; // or you can use an ArrayList
int numwords;
// constructor: read words from a file
public Dictionary(String filename){ }
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOExecption e) {
e.printStackTrace();
}
}

Reading strings into array:
Automatic:
List<String> strings = Files.readAllLines(Path);
Manual:
List<String> strings = new ArrayList<>();
while ((line = br.readLine()) != null){
strings.add(line);
}
Splitting lines to words (if one line contains several words):
for(String s : strings) {
String[] words = s.split(" "); //if words in line are separated by space
}

This could be helpful too:
class Dictionary{
ArrayList<String> words = new ArrayList<String>(); // or you can use an ArrayList
int numwords;String filename;
// constructor: read words from a file
public Dictionary(String filename){
this.filename =filename;
}
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
words.add(line.trim());
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
I have used trim which will remove the leading and the trailing spaces from the words if there are any.Also, if you want to pass the filename as a parameter use the filename variable inside Filereader as a parameter.

Yes, you can use an arrayList to store the words you are looking to add.
You can simply use the following to deserialize the file.
ArrayList<String> pList = new ArrayList<String>();
public void deserializeFile(){
try{
BufferedReader br = new BufferedReader(new FileReader("file_name.txt"));
String line = null;
while ((line = br.readLine()) != null) {
// assuming your file has words separated by space
String ar[] = line.split(" ");
Collections.addAll(pList, ar);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}

Related

Replace defined words in a file with replacements in another file - Java

I have a file (file1.txt) containing:
word word word2 word word1
word2 word word 1
The other file (file2.txt) contains:
word1-replacement1
word2-replacement2
I need a method looking up if the words from file2 are contained in file1 and if they are contained replace those words with the replacement.
I already have following:
BufferedReader br = new BufferedReader(new FileReader("file2.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("file1.txt"));
String line;
String line2;
while ((line = br.readLine()) != null) {
String vars[] = line.split("-");
String varname = vars[0];
String replacement = vars[1];
while ((line2 = br2.readLine()) != null) {
if(line2.contains(varname)) {
line2.replace(varname, replacement);
}
}
}
The problem with this code is, that it just reads only the first line of file1.
The final output should look like:
word word replacement2 word replacement1
replacement2 word replacement1
Thanks for your help :)
I suggest first reading in the second file into Java memory, and storing the data as a key value store in a hashmap. Then, iterate over the lines from the first file, and make any matching replacements.
Map<String, String> map = new HashMap<>();
String line = "";
try (BufferedReader br = new BufferedReader(new FileReader("file2.txt"))) {
while ((line = br.readLine()) != null) {
String[] parts = line.split("-");
map.put(parts[0], parts[1]);
}
}
catch (IOException e) {
// handle exception
}
try (BufferedReader br = new BufferedReader(new FileReader("file1.txt"))) {
while ((line = br.readLine()) != null) {
for (Map.Entry< String, String > entry : map.entrySet()) {
String pattern = "\\b" + entry.getKey() + "\\b";
line = line.replaceAll(pattern, entry.getValue());
// now record the updated line; printed to the console here for demo purposes
System.out.println(line);
}
}
}
catch (IOException e) {
// handle exception
}
Note carefully that I call String#replaceAll above with word boundaries around each term. This matters because, for example, without boundaries the term word1 would match something like aword1term, that is, it would match word1 even as a substring of some other word.
You can start by creating a Map of replacements like so:
public Map<String,String> getReplacements(File file) throws FileNotFoundException {
Map<String, String> replacementMap = new HashMap<>();
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
String line = sc.nextLine();
String [] replacement = line.split("-");
String from = replacement[0];
String to = replacement[1];
replacementMap.put(from,to);
}
return replacementMap;
}
And then use the map to replace the words in the other file.

How to remove the duplicate string?

In my code I have two files in my drive those two files have some text and I want to display those string in the console and also remove the repeated string and display the repeated string once rather than displaying it twice.
Code:
public class read {
public static void main(String[] args) {
try{
File file = new File("D:\\file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while((line = br.readLine()) != null){
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file1:");
String first = stringBuffer.toString();
System.out.println(first);
File file1 = new File("D:\\file2.txt");
FileReader fileReader1 = new FileReader(file1);
BufferedReader br1 = new BufferedReader(fileReader1);
StringBuffer stringBuffer1 = new StringBuffer();
String line1;
while((line1 = br1.readLine()) != null){
stringBuffer1.append(line1);
stringBuffer1.append("\n");
}
fileReader1.close();
System.out.println("Contents of file2:");
String second = stringBuffer1.toString();
System.out.println(second);
System.out.println("answer:");
System.out.println(first+second);
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Output is:
answer:
hi hello
how are you
hi ya
i am fine
But I want to compare both the strings and if the same string repeated then that string should be displayed once.
Output I expect is like this:
answer:
hi hello
how are you
ya
i am fine
Where the "hi" is found in both the strings so that I need to delete the one duplicate string.
How can I do that please help.
Thanks in advance.
You can pass your lines through this method to parse out duplicate words:
// store unique previous words
static Set<String> words = new HashSet<>();
static String removeDuplicateWords(String line) {
StringJoiner sj = new StringJoiner(" ");
// split on whitespace to get distinct words
for (String word : line.split("\\s+")) {
// try to add word to the set
if (words.add(word)) {
// if the word was added (=not seen before), append to the result
sj.add(word);
}
}
return sj.toString();
}

search a word inside file then stored in array

my problem is i read a file then i search a word "(:types"
i want take the words after "(:types" but the code take a line after "(:types"
this is the problem i need to you to find why my code cant store words after
"(:types" ( my code take "
location vehicle cargo)" i need to take ( "space fuel
location vehicle cargo")
sorry for my English
(:types space fuel
location vehicle cargo)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
public class type2 {
public static void main(String[] args){
String filePath = "C:\\test4.txt";
BufferedReader br;
String line = "";
String read=null;
List<String> temps = new LinkedList<String>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while((line = br.readLine()) != null)
{
String[] words = line.split(" ");
for (String word : words) {
if (word.equals("(:types") ) {
while((read = br.readLine()) != null){
temps.add(read);
if (word.equals("(:predicates") );
break;
}
String[] tempsArray = temps.toArray(new String[0]);
String [] type=tempsArray[0].split(" ");
System.out.println(tempsArray[0]);
}
}
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The reason you aren't getting the words that are on the same line is because you don't parse the rest of the line.
First you get the first line with
while((line = br.readLine()) != null)
And then split that on all the spaces with:
String[] words = line.split(" ");
But once you find the string (:types, all you do is start reading from the file again. You never parse the remaining parts of the array words.
If you want to parse the rest of this array, maybe find the index of the string (:types in your array, then just parse all parts after it.
The problem seem very straightforward.
If I understand you correctly you have a file which contain the lines:
(:types space fuel
location vehicle cargo)
You want to find the line containing "(:types" and then save "space" and "fuel".
In your code your read in a new line of text like this
while((line = br.readLine()) != null)
You check line for whether it contains (:types and if it does you store the words in the next line through the code:
while((read = br.readLine()) != null){
temps.add(read);
This above is your problem. To fix this you should change the above code to the following:
for (String word : words){
if(!word.equals("(:types")){
temps.add(read);
}
}

Splitting error- IndexOutOfBoundsException

I got stuck with an issue, that I can't seem to solve. When splitting I should be able to get id, name, check by setting row[0], row[1], row[2]. Strangely only row[0] (id) seem to work. Name, check gives me an error. Could someone help me further?
Example of data:
id,name,check
1,john,0
1,patrick,0
1,naruto,0
Code:
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(Pattern.quote(","));
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
Error message:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
Solved
It seems I had an incorrect value (question marks) at end of file. When removing this line. My code worked (without Patter.quote). Thank you all for fast reply's. First answer helped me on reminding me of using Log value where I could see the 'incorrect value'. My bad.
Probably in the time:
String[] row = line.split(",");
was called, there was no comma (,) in the line of the file/stream you're trying to read.
Try this code,
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(",");
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
I think you don't need to use Pattern.quote(",") here.
In my experience with txt files this is the best way of dealing with it:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class Cyto {
public static void main(String[] args) throws IOException {
ArrayList<String> names = new ArrayList<String>();
try {
FileInputStream dis = new FileInputStream("list.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while (br.ready()) {
line = br.readLine();
String[] row = line.split(Pattern.quote(","));
System.out.println(row[1]);
names.add(row[1]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use
br.ready()
instead of reading directly from stream.

Reading a text file in java

How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.
I'm a complete noob in Java so sorry if this question is a bit stupid.
Thanks
Try the Scanner class which no one knows about but can do almost anything with text.
To get a reader for a file, use
File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (file), encoding));
... use reader ...
reader.close ();
You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.
Easiest option is to simply use the Apache Commons IO JAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;
List<String> lines = FileUtils.readLines(new File("untitled.txt"));
It's that easy.
"Don't reinvent the wheel."
The best approach to read a file in Java is to open in, read line by line and process it and close the strea
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console - do what you want to do
System.out.println (strLine);
}
//Close the input stream
fstream.close();
To learn more about how to read file in Java, check out the article.
Your question is not very clear, so I'll only answer for the "read" part :
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
lines.add(line);
line = br.readLine();
}
Common used:
String line = null;
File file = new File( "readme.txt" );
FileReader fr = null;
try
{
fr = new FileReader( file );
}
catch (FileNotFoundException e)
{
System.out.println( "File doesn't exists" );
e.printStackTrace();
}
BufferedReader br = new BufferedReader( fr );
try
{
while( (line = br.readLine()) != null )
{
System.out.println( line );
}
#user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[500];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
This is a nice way to work with Streams and Collectors.
List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
myList = reader.lines() // This will return a Stream<String>
.collect(Collectors.toList());
}catch(Exception e){
e.printStackTrace();
}
When working with Streams you have also multiple methods to filter, manipulate or reduce your input.
For Java 11 you could use the next short approach:
Path path = Path.of("file.txt");
try (var reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Or:
var path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
Or:
Files.lines(Path.of("file.txt")).forEach(System.out::println);

Categories

Resources