Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
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...
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"
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.
Read String line by line in Java
How to split a comma separated String while ignoring escaped commas?
Reading File by line instead of word by word
Read line using Java New I/O
CSV API for Java
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]);
}
}
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.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
I need help in constructing a String array in Java which would store values from a text file (.txt). The file has 82094 lines where each line contains 1 word. So, in total there are 82094 words that I want to add to my array.
Here is the file path :
"F:/Word Game/Words List [UK ENGLISH].txt"
I have declared this array :
String words[]=new String[82094];
I'm not sure what to do next.
First of all, you need to read your file line by line, then put each line in an array. I strongly recommend you to use one of java.util.List<E>'s instances. I prefer java.util.ArrayList<E>
In short, ArrayList is more flexible than a plain native array because it's dynamic. It can grow itself when needed, which is not possible with the native array. ArrayList also allows you to remove elements that are not possible with native arrays. You can read more about it here.
List<String> words = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("YOUR_FILE_PATH"))) {
String line;
while ((line = br.readLine()) != null) {
words.add(line);
}
}
Also since java 8, you can use java.util.Stream<T> to read a file:
List<String> words = new ArrayList<String>();
try (Stream<String> lines = Files.lines(Paths.get("YOUR_FILE_PATH"), Charset.defaultCharset())) {
lines.forEachOrdered(line -> words.add(line));
}
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I have a text file that contains names followed by .xml such as georgeeliot.xml I then took the text file and placed it into a string. I am now trying to figure out how to loop through the string and place each name.xml into a ArrayList that I created ArrayList<String> items = new ArrayList<String>();
I've done some research, but most examples I can find put them into an array. Thanks for your help.
`
You don't share what your delimiter is, but something like this will work:
final String DELIMITER = " "; // using space
String example = "one.xml two.xml three.xml";
List<String> items = Arrays.asList(example.split(DELIMITER));
for (String item : items) { // test output
System.out.println(item);
}
You'd probably be best just adding it to the List when you read the file unless you need the String representing the file contents for some other purpose. For example using Scanner:
Scanner sc = new Scanner(new File("file.txt")); // default delimiter is whitespace
/**
* or if using a custom delimiter:
* final String DELIMITER = " "; // using space
* Scanner sc = new Scanner("file.txt").useDelimiter(DELIMITER);
*/
List<String> items = new ArrayList<>();
while (sc.hasNext()) {
items.add(sc.next());
}
for (String item : items) { // test output
System.out.println(item);
}
file.txt
one.xml
two.xml
three.xml
I am trying to search for words within a text file and replace all upper-cased with lower-cased characters. The problem is that when I use the replace All function using a regular expression I get a syntax error. I have tried different tactics, but it doesn't work. Any tips? I think that maybe I should create a replace All method that I would have to invoke, but I don't really see its use.
public static void main() throws FileNotFoundException {
ArrayList<String> inputContents = new ArrayList<>();
Scanner inFile =
new Scanner(new FileReader("H:\\csc8001\\data.txt"));
while(inFile.hasNextLine())
{
String line = inFile.nextLine();
inputContents.add(inFile.nextLine());
}
inFile.close();
ArrayList<String> dictionary = new ArrayList<>();
for(int i= 0; i <inputContents.size(); i++)
{
String newLine = inFile.nextLine();
newLine = newLine(i).replaceAll("[^A-Za-z0-9]");
dictionary.add(inFile.nextLine());
}
// PrintWriter outFile =
// new PrintWriter("H:\\csc8001\\results.txt");
}
There is a compilation error on this line:
newLine = newLine(i).replaceAll("[^A-Za-z0-9]");
Because replaceAll takes 2 parameters: a regex and a replacement.
(And because newLine(i) is non-sense.)
This should be closer to what you need:
newLine = newLine.replaceAll("[^A-Za-z0-9]+", " ");
That is, replace non-empty sequences of non-[A-Za-z0-9] characters with a space.
To convert all uppercase letters to lowercase, it's simpler and better to use toLowerCase.
There are many other issues in your code too. For example, some lines in the input will be skipped, due to some inappropriate inFile.nextLine calls. Also, the input file is closed after the first loop, but the second tries to use it, which makes no sense.
With these and a few other issues cleaned up, this should be closer to what you want:
Scanner inFile = new Scanner(new FileReader("H:\\csc8001\\data.txt"));
List<String> inputContents = new ArrayList<>();
while (inFile.hasNextLine()) {
inputContents.add(inFile.nextLine());
}
inFile.close();
List<String> dictionary = new ArrayList<>();
for (String line : inputContents) {
dictionary.add(line.replaceAll("[^A-Za-z0-9]+", " ").toLowerCase());
}
If you want to add words to the dictionary instead of lines, you also need to split the lines on spaces. One simple way to achieve that:
dictionary.addAll(Arrays.asList(line.replaceAll("[^A-Za-z0-9]+", " ").toLowerCase().split(" ")));
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
The method should read the contents of a file line by line and add each line to the array list. It should end once it reaches a solitary "." (period) or no more lines.
The problem is that I can not figure a way to check the contents of the next line without skipping lines since I am using nextLine numerous times. I am limited to the use of hasNext and nextLine.
public static ArrayList<String> getList(Scanner in) {
ArrayList<String> list = new ArrayList<String>();
while(in.hasNext() && !in.nextLine().equals("."))
{list.add(in.nextLine());}
return list;}
As written the output will skip lines to output lines 2, 4, 6 etc
when I need it to output 1,2,3,4 etc.
I am sure I am simply not seeing the way to solve the issue but any hints specifically on how to get it working by reformatting what I have with the methods listed are appreciated.
Just store the line in a variable:
public static List<String> getList(Scanner in) {
List<String> list = new ArrayList<String>();
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals(".")) {
break;
}
else {
list.add(line);
}
}
return list;
}
I need to make a dictionary that takes words from a .txt file. These words (separated line by line) need to be stored in a String array. I have already gotten to the point of separating the words and adding them to a new .txt file, but I have no idea how to add them each to a String array. There are
You need to count the lines in the file. Create an array of that size.
Then for each line in the file, read it and insert it into the array at the index[lineReadFrom].
Since you are not allowed to use ArrayList or LinkedList objects, I would suggest to save every found word "on the fly" while you are reading the input file. These is a series of steps you could follow to get this done:
1. Read the file, line by line: Use the common new BufferedReader(new FileInputStream("/path/to/file")) approach and read line by line (as I assume you are already doing, looking at your code).
2. Check every line for words: Break every possilbe word by spaces with a String.split() and remove punctuation characters.
3. Save every word: Loop through the String array returned by the String.split() and for every element that you considered a word, update your statistics and write it to your dictionary file with the common new BufferedWriter(new FileWriter("")).write(...);
4. Close your resources: Close the reader an writer after you finished looping through them, preferably in a finally block.
Here is a complete code sample:
public static void main(String[] args) throws IOException {
File dictionaryFile = new File("dict.txt");
// Count the number of lines in the file
LineNumberReader lnr = new LineNumberReader(new FileReader(dictionaryFile));
lnr.skip(Long.MAX_VALUE);
// Instantiate a String[] with the size = number of lines
String[] dict = new String[lnr.getLineNumber() + 1];
lnr.close();
Scanner scanner = new Scanner(dictionaryFile);
int wordNumber = 0;
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
if (word.length() >= 2 && !(Character.isUpperCase(word.charAt(0)))) {
dict[wordNumber] = word;
wordNumber++;
}
}
scanner.close();
}
It took about 350 ms to finish executing on a 118,620 line file, so it should work for your purposes. Note that I instantiated the array in the beginning instead of creating a new String[] on each line (and replacing the old one like you did in your code).
I used wordNumber to keep track of the current array index so that each word would be added to the array at the right location.
I also used .nextLine() instead of .next() since you said that the dictionary was separated by line instead of by spaces (which is what .next() uses).