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).
Related
I want to read the contents of a text file, split on a delimiter and then store each part in a separate array.
For example the-file-name.txt contains different string all on a new line:
football/ronaldo
f1/lewis
wwe/cena
So I want to read the contents of the text file, split on the delimiter "/" and store the first part of the string before the delimiter in one array, and the second half after the delimiter in another array. This is what I have tried to do so far:
try {
File f = new File("the-file-name.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null) {
String[] parts = readLine.split("/");
}
} catch (IOException e) {
e.printStackTrace();
}
This is what I have achieved so far but I am not sure how to go on from here, any help in completing the program will be appreciated.
You can create two Lists one for the first part and se second for the second part :
List<String> part1 = new ArrayList<>();//create a list for the part 1
List<String> part2 = new ArrayList<>();//create a list for the part 2
while ((readLine = b.readLine()) != null) {
String[] parts = readLine.split("/");//you mean to split with '/' not with '-'
part1.add(parts[0]);//put the first part in ths list part1
part2.add(parts[1]);//put the second part in ths list part2
}
Outputs
[football, f1, wwe]
[ronaldo, lewis, cena]
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());
}
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(",");
a:b:c:d:e
bb:cc:dd:ee:ff
ccc:ddd:eee:fff:ggg
I have a textfile content above. I am trying to compare my user input with the text file. For example
cc:dd
When it is found, I need to retrieve the entire line. How can I retrieve the line which my user input? I have tried using while(scanner.hasNext()) but I could not get my desire outcome.
With standard Java libraries:
File file = new File("file.txt");
String word = "abc";
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch(FileNotFoundException e) {
//handle this
}
//now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains(word)) {
System.out.println(line);
}
}
scanner.close();
I have a text file that has following content:
ac und
accipio annehmen
ad zu
adeo hinzugehen
...
I read the text file and iterate through the lines:
Scanner sc = new Scanner(new File("translate.txt"));
while(sc.hasNext()){
String line = sc.nextLine();
}
Each line has two words. Is there any method in java to get the next word or do I have to split the line string to get the words?
You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.
You can just create a new Scanner object within your while statement.
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("translate.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
System.out.println(s);
}
}
You already get the next line in this line of your code:
String line = sc.nextLine();
To get the words of a line, I would recommend to use:
String[] words = line.split(" ");
Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().
On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.
P.S.: Sorry, I don't have right to comment on already given answers.
you're better off reading a line and then doing a split.
File file = new File("path/to/file");
String words[]; // I miss C
String line;
HashMap<String, String> hm = new HashMap<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")))
{
while((line = br.readLine() != null)){
words = line.split("\\s");
if (hm.containsKey(words[0])){
System.out.println("Found duplicate ... handle logic");
}
hm.put(words[0],words[1]); //if index==0 is ur key
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can just use Scanner to read word by word, Scanner.next() reads the next word
try {
Scanner s = new Scanner(new File(filename));
while (s.hasNext()) {
System.out.println("word:" + s.next());
}
} catch (IOException e) {
System.out.println("Error accessing input file!");
}