I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this:
1:John:false
2:Bob:false
3:Audrey:false
How can I create an ArrayList from the text file for each line?
Read from a file and add each line into arrayList. See the code for example.
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(<your_file_path>)))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
arr.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
While the answer above me works, here's another way to do it. Make sure to import java.util.Scanner.
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner("YOURFILE.txt");
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in following example:
BufferedReader bufReader = new BufferedReader(new
FileReader("file.txt"));
ArrayList<String> listOfLines = new ArrayList<>);
String line = bufReader.readLine(); while (line != null)
{
listOfLines.add(line);
line = bufReader.readLine();
}
bufReader.close();
Just remember to close the BufferedReader once you are done to prevent resource leak, as you don't have try-with-resource statement
This will be help to you.
List<String> list = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("list.txt"));
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
reader.close();
Then you can access those elements in the arraylist.
java 8 lets you do this
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
list = stream
.map(String::toUpperCase)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
list.forEach(System.out::println);
Related
I have some very simple code to ready content of txt file, line by line and put it into String[], however buffered reader return all lines as "null" - any idea on what might be the reason? *I want to use buffered reader and not other options as this is just part of java training excersise and mostly I want to understand where is the mistake i made. thanks!
public static void readFile (String path){
File file = new File(path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int lineCount = (int) br.lines().count();
String[] passwords = new String[lineCount];
for (int i=0; i<lineCount; i++){
passwords[i] = br.readLine();;
System.out.println(passwords[i]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
By using the lines() method you basically move the buffered reader position to the end of the file. It's like you already read these lines.
Try using this in order to iterate through all lines:
while ((line = br.readLine()) != null) {
// Use the line variable here
}
Use br.lines() or br.readLine() to consume the input, but not both at the same time. This version does the same using just the stream to String[], and closes the inputs in try with resources block:
public static String[] readFile(Path path) throws IOException {
try (BufferedReader br = Files.newBufferedReader(path);
Stream<String> stream = br.lines()) {
return stream.peek(System.out::println)
.collect(Collectors.toList())
.toArray(String[]::new);
}
}
String[] values = readFile(Path.of("somefile.txt"));
My method read and prints the file, but I am having trouble adding each word to the ArrayList dict.
The reader reads the file one char at a time, so what I have written adds each char to dict: [c,a,t,d,o,g] when I want [cat,dog]. The text file has the words on their own line; how can I distinguish them?
My code so far:
public static List Dictionary() {
ArrayList <String> dict = new ArrayList <String>();
File inFile = new File("C:/Users/Aidan/Desktop/fua.txt");
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
dict.add((char) ch + "");
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
return dict;
}
Please observe Java naming conventions, so readDictionary instead of Dictionary (which looks like a class name). Next, I would pass the fileName into the method (instead of hard-coding the path in your method). Instead of reinventing the wheel, I would use a Scanner. You can also use the try-with-resources instead of finally here (and the diamond operator). Like,
public static List<String> readDictionary(String fileName) {
List<String> dict = new ArrayList<>();
try (Scanner scan = new Scanner(new File(fileName))) {
while (scan.hasNext()) {
dict.add(scan.next());
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
return dict;
}
Alternatively, use a BufferedReader and split each word yourself. Like,
public static List<String> readDictionary(String fileName) {
List<String> dict = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(
new File(fileName)))) {
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
Stream.of(line.split("\\s+"))
.forEachOrdered(word -> dict.add(word));
}
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
return dict;
}
But that is basically what the first example does.
Check out the answer here which shows how to use Scanner to get words from a file: Read next word in java.
Instead of printing out the words, you'd want to append them to an ArrayList.
As the read method of the FileReader can only read a single character at a time and that's not what you want, then I would suggest you use a Scanner to read the file.
ArrayList<String> dict = new ArrayList<>();
Scanner scanner = new Scanner(new File("C:/Users/Aidan/Desktop/fua.txt"));
while(scanner.hasNext()){
dict.add(scanner.next());
}
You can wrap your FileReader in a BufferedReader, which has a readLine() method that will get you an entire line (word) at a time. readLine() returns null when there are no more lines to read.
I'm new to coding in java. Can anyone help me with my codes? I'm currently making a program where you input a string in a jTextArea, and if the input word(s) matches the one in the text file then it will then do something.
For example: I input the word 'Hey' then it will print something like "Hello" when the input word matches from the text file.
I hope you understand what I mean.
Here's my code:
String line;
String yo;
yo = jTextArea2.getText();
try (
InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
)
{
while ((line = br.readLine()) != null) {
if (yo.equalsIgnoreCase(line)) {
System.out.print("Hello");
}
}
} catch (IOException ex) {
Logger.getLogger(ArfArf.class.getName()).log(Level.SEVERE, null, ex);
}
You can not use equals for line because a line contain many words. You have to modify it to search the index of the word in a line.
try (InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
yo = yo.toLowerCase();
if (line.indexOf(yo) != -1) {
System.out.print("Hello");
}
line = br.readLine();
}
} catch (IOException ex) {
}
since you are new in java , I would suggest you to take some time to study java 8 which enable to write more clean codes. below is the solution write in java 8, hope can give a kind of help
String yo = jTextArea2.getText();
//read file into stream,
try (java.util.stream.Stream<String> stream = Files.lines(Paths.get("readme.txt"))) {
List<String> matchLines = stream.filter((line) -> line.indexOf(yo) > -1).collect(Collectors.toList()); // find all the lines contain the text
matchLines.forEach(System.out::println); // print out all the lines contain yo
} catch (IOException e) {
e.printStackTrace();
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordFinder {
public static void main(String[] args) throws FileNotFoundException {
String yo = "some word";
Scanner scanner = new Scanner(new File("input.txt")); // path to file
while (scanner.hasNextLine()) {
if (scanner.nextLine().contains(yo)) { // check if line has your finding word
System.out.println("Hello");
}
}
}
}
I want every line in my textdoc to be assigned to a variable.
import java.io.*;
import static java.lang.System.*;
class readfile {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("filename");
BufferedReader br = new Buffered(fr);
String str;
while ((str = br.readLine()) != null) {}
br.close();
} catch (IOException e) {
out.println("file not found");
}
}
}
I would suggest you create a List and store every line in a list like below:
String str;
List<String> fileText = ....;
while ((str = br.readLine()) != null) {
fileText.add(str);
}
A Java 8 solution for creating a List of lines
Path path = Paths.get("filename");
List<String> lines = Files.lines(path).collect(Collectors.toList());
why do you want to add each line to a separate variable? It is better to add the lines to a list. Then you can access any line as you want.
In JDK 6 or below
List<String> lines = new ArrayList<String>();
while(reader.ready())
lines.add(reader.readLine());
In JDK 7 or above
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
I would do
List<string> allText= new List<String>();
While(str.hasNextLine){
allText.add(str.nextLine);
}
I have a text file containing words separated by newline , like the following format:
>hello
>world
>example
How do i create an ArrayList and store each word as an element?
You can use apache commons FileUtils.readLines().
I think the List it returns is already an ArrayList, but you can use the constructor ArrayList(Collection) to make sure you get one.
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
File file = new File("names.txt");
ArrayList<String> names = new ArrayList<String>();
Scanner in = new Scanner(file);
while (in.hasNextLine()){
names.add(in.nextLine());
}
Collections.sort(names);
for(int i=0; i<names.size(); ++i){
System.out.println(names.get(i));
}
The simplest way is to use Guava:
File file = new File("foo.txt");
List<String> words = Files.readLines(file, Charsets.UTF_8);
(It's not guaranteed to be an ArrayList, but I'd hope that wouldn't matter.)
You read the file line-by-line, create an ArrayList for Strings, and add line.substring(1) to the defined ArrayList if line.length>0.
I put the file at "C:\file.txt"; if you run the following it fils an ArrayList with the words and prints them.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:\\file.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<String>();
String line = br.readLine();
while(line != null) {
lines.add(line.replace(">", ""));
line = br.readLine();
}
for(String l : lines) {
System.out.println(l);
}
}
}
I'm sure they're lots of libraries that do this with 1 line, but here's a "pure" Java implementation:
Notice that we've "wrapped"/"decorated" etc. a standard FileReader (which only has read one byte at a time) with a BufferedReader which gives us a nicer readLine() method.
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("test.txt"),
Charset.forName("ISO-8859-1")));
List<String> lines = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
System.out.println(lines);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}