1

Hello, I want to read a file, file.txt that contains word pairs like this...

mot;word 
oui;yes
utiliser;use
comment;how

After reading this file.txt , I want to split this text and put the French words in an ArrayList and the English words in an another ArrayList.

Thanks in advance...

Buddhima Gamlath
  • 2,218
  • 12
  • 25
user3144878
  • 47
  • 1
  • 1
  • 3

4 Answers4

8
public static void main(String[] args) {
    List<String> list = new ArrayList<String>(); 
    List<String> frenchList = new ArrayList<String>();
    List<String> englishList = new ArrayList<String>();
    File file = new File("C:/dico.txt");
    if(file.exists()){
        try { 
            list = Files.readAllLines(file.toPath(),Charset.defaultCharset());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
      if(list.isEmpty())
          return;
    }
    for(String line : list){
        String [] res = line.split(";");
        frenchList.add(res[0]);
        englishList.add(res[1]);
    }
}

With this code you have de french word in the list "frenchlist" and the english words in the list "englishlist"

beny1700
  • 284
  • 1
  • 4
  • 10
2

This looks like CSV file. Consider using CSV reader library.

Use String#split function from JDK and read file line by line with Scanner:

Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  // process the line using String#split function
}

In while loop add splited data to ArrayList.

All information are already on stackoverflow.

Community
  • 1
  • 1
MariuszS
  • 27,972
  • 12
  • 103
  • 144
2

First, you have to create two array lists..

    ArrayList<String> english = new ArrayList<>();
    ArrayList<String> french = new ArrayList<>();

Then, open the file, read line by line, split it bye ";" and add the words to ArrayLists...

    try(BufferedReader in = new BufferedReader(new FileReader("file.txt"))){
      String line;
      while((line = in.readLine())!=null){
          String[] pair = line.split(";");
          french.add(pair[0]);
          english.add(pair[1]);
      }
    }
Buddhima Gamlath
  • 2,218
  • 12
  • 25
0
mot;word 
oui;yes
utiliser;use
comment;how

It appears that the structure of each line is

frenchWord;englishWord

So you can read each line of your file using a Scanner (using the constructor Scanner(File source)) and the nextLine() method, and split each line by ";".

The first element in the array will be the french word and the second one the english word.

Add those element in two separate List (ArrayList per example), one containing all the french words, and the other one the english words.

user2336315
  • 14,237
  • 9
  • 37
  • 63