If I got a .txt file named words.txt and I want to catch the words to input them into an arraylist how do I do that. I know buffered reader exists but I dont quite get how to use it. All words are seperated by a space or an enter key. It has to then for example filter out words that are not 4 characters long and place the 4 long words in an arraylist to use later.
For example I got this txt file :
one > gets ignored
two > gets ignored
three > gets ignored
four > caught and put into for example arraylist
five > 4 long so gets caught and put into arraylist
six > ignored
seven > ignored
eight > ignored
nine > caught because its 4 char long
ten > ignored
You can do it using streams and NIO.2
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Path path = Paths.get("words.txt");
try (Stream<String> lines = Files.lines(path)) {
List<String> list = lines.filter(word -> word.length() == 4)
.collect(Collectors.toList());
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Here is my words.txt file:
one
two
three
four
five
six
seven
eight
nine
ten
And running the above code, using the above file, prints the following:
[four, five, nine]
Alternatively, you can use a Scanner
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Path source = Paths.get("words.txt");
try (Scanner scanner = new Scanner(source)) {
List<String> list = new ArrayList<>();
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
if (word.length() == 4) {
list.add(word);
}
}
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Note that both the above versions of class Main use try-with-resources.
Yet another way is to use class java.io.BufferedReader (since you mentioned it in your question).
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
File f = new File("words.txt");
try (FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
List<String> list = new ArrayList<>();
String line = br.readLine();
while (line != null) {
if (line.length() == 4) {
list.add(line);
}
line = br.readLine();
}
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Related
Let's say I have theese words in a text file
Dictionary.txt
artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
How can I make each word a different object and print them on the console?
You can simple use Scanner.nextLine(); function.
Here is the following code which can help
also import the libraries
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
Use following code:-
String []words = new String[1];
try{
File file = new File("/path/to/Dictionary.txt");
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
words[i]=scan.nextLine();
i++;
words = Arrays.copyOf(words,words.legnth+1); // Increasing legnth of array with 1
}
}
catch(Exception e){
System.out.println(e);
}
You must go and research on Scanner class
This is a very simple solution using Files:
package org.kodejava.io;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
public class ReadFileAsListDemo {
public static void main(String[] args) {
ReadFileAsListDemo demo = new ReadFileAsListDemo();
demo.readFileAsList();
}
private void readFileAsList() {
String fileName = "Dictionary.txt";
try {
URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
List<String> lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Source: https://kodejava.org/how-do-i-read-all-lines-from-a-file/
This is another neat solution using buffered reader:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* BufferedReader and Scanner can be used to read
line by line from any File or
* console in Java.
* This Java program
demonstrate line by line reading using BufferedReader in Java
*
* #author Javin Paul
*/
public class BufferedReaderExample {
public static void main(String args[]) {
//reading file line by line in Java using BufferedReader
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("C:/sample.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading
File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Source: https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html#axzz7lrQcYlyy
These are all good answers. The OP didn't state what release of Java they require, but in modern Java I'd just use:
import java.nio.file.*;
public class x {
public static void main(String[] args) throws java.io.IOException {
Files.lines(Path.of("/path/to/Dictionary.txt")).forEach(System.out::println);
}
}
I have a folder which has a series of Zip files within it. I am trying to iterate through the folder and count the number of files that are in each zip file. I have created two pieces of code, I am just not sure how to put them together to get my desired results. Both codes are placed into try/catch blocks and they both work perfectly independently. This is using Eclipse, written in Java.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.zip.ZipFile;
import java.io.File;
import java.util.List;
public class KZF {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Try/Catch Block counts the number of files within a given zip file
try {
ZipFile zipFile = new ZipFile(
"C:\\Users\\username\\Documents\\Temp\\AllKo\\Policy.zip");
int NumberOfFiles = zipFile.size() - 1;
// String name = zipFile.getName();
Path path = Paths
.get("C:\\Users\\username\\Documents\\Temp\\AllKo\\Policy.zip");
Path filename = path.getFileName();
System.out.print("The number of files in: ");
// System.out.print(name);
System.out.print(filename.toString());
System.out.print(" are: ");
System.out.print(NumberOfFiles + " file(s)");
zipFile.close();
}
catch (IOException ioe) {
System.out.println("Error opening zip file" + ioe);
}
// ----------------------------------------------------------------------------------------------------------
// Creates list of every file specified folder
String dirLocation = "C:\\Users\\username\\Documents\\Temp\\AllKo";
try { List<File> files = Files.list(Paths.get(dirLocation))
.map(Path::toFile) .collect(Collectors.toList());
files.forEach(System.out::println);
} catch(IOException e) { Error }
}
}
You must be careful about opening/closing streams, so you can try something like this:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class KZF
{
static int findNumberOfFiles(File file) {
try (ZipFile zipFile = new ZipFile(file)) {
return zipFile.stream().filter(z -> !z.isDirectory()).count();
} catch (Exception e) {
return -1;
}
}
static String createInfo(File file) {
int tot = findNumberOfFiles(file);
return (file.getName() + ": " + (tot >= 0 ? tot + " files" : "Error reading zip file"));
}
public static void main(String[] args) throws IOException {
String dirLocation = "C:\\Users\\username\\Documents\\Temp\\AllKo";
try (Stream<Path> files = Files.list(Paths.get(dirLocation))) {
files
.filter(path -> path.toFile().isFile())
.filter(path -> path.toString().toLowerCase().endsWith(".zip"))
.map(Path::toFile)
.map(KZF::createInfo)
.forEach(System.out::println);
}
}
}
I'm a java beginner and I'm doing a small project about dictionary, now I want to save word and translate mean in file, because my native language often have space like chicken will be con gà so, I must use other way, not by space, but I really don't know how to do that, a word and it translation in one line, separate by "tab", mean multi space like chicken con gà now I want to get 2 words and store it in my array of Words which I created before, so I want to do something like
w1=word1inline;
w2=word2inline;
Word(word1inline,word2inline);(this is a member of array);
please help me, thanks a lot, I just know how to read line from file text, and use split to get word but I am not sure how to read by multi space.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class docfile {
public static void main(String[] args)
{
String readLine;
ArrayList<String>str=new ArrayList<>(String);
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((readLine = b.readLine()) != null) {
str.add()=readLine.split(" ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you stick to using tabs as a separator, this should work:
package Application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Application {
public static void main(String[] args) {
String line;
ArrayList<String> str = new ArrayList<>();
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((line = b.readLine()) != null) {
for (String s : line.split("\t")) {
str.add(s);
}
}
str.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why not just use a properties file?
dict.properties:
chicken=con gá
Dict.java:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
public class Dict {
public static void main(String[] args) throws IOException {
Properties dict = new Properties();
dict.load(Files.newBufferedReader(Paths.get("dict.properties")));
System.out.println(dict.getProperty("chicken"));
}
}
Output:
con gá
If your line is like this chicken con gà you can use indexof() method to find the first space in the string.
Then you can substring each word by using substring() method.
readLine = b.readLine();
ArrayList<String>str=new ArrayList<>();
int i = readLine.indexOf(' ');
String firstWord = readLine.substring(0, i);
String secondWord = readLine.substring(i+1, readLine.length());
str.add(firstWord);
str.add(secondWord);
This program takes in input the "hello my name is bob" and spits it out backwards. I really need help making it that the program reads in a text file and spits out the text file backwards. Thanks in advance!
public class Recursion
{
public static void main(String[] args) throws FileNotFoundException {
System.out.println(printBackwards("hello my name is bob"));
}
public static String printBackwards(String s){
if(s.length() <= 1)
return s;
else
return printBackwards(s.substring(1,s.length()))+s.charAt(0);
}
}
Based on the comments for the question, this will read a file called input.txt and save it to a new file called output.txt using your method for reversing a String.
All lines in input.txt are firstly added to a List.
The List is then iterated through backwards from the last element, and with each iteration the reversed String written to output.txt.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
Scanner scanner = new Scanner(new File("input.txt"));
List<String> fileContents = new ArrayList<>();
while (scanner.hasNextLine()) {
fileContents.add(scanner.nextLine());
}
ListIterator<String> it = fileContents.listIterator(fileContents.size());
while (it.hasPrevious()) {
writer.write(printBackwards(it.previous()));
writer.newLine();
}
}
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
If however you just want to display it to the standard output, you can adjust it to the following:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("input.txt"));
List<String> fileContents = new ArrayList<>();
while (scanner.hasNextLine()) {
fileContents.add(scanner.nextLine());
}
ListIterator<String> it = fileContents.listIterator(fileContents.size());
while (it.hasPrevious()) {
System.out.println(printBackwards(it.previous()));
}
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
Or as I said in my comment earlier, you can just read the whole file in one go and reverse it:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(printBackwards(new Scanner(new File("file.txt")).useDelimiter("\\Z").next()));
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
Use this code to get the string that you want to reverse from a text file:
try{
String myString;
BufferedReader input = new BufferedReader(new FileReader("Filepath.txt");
while((myString = input.readLine()) != null){}
}
catch(FileNotFoundException ex){
//Error Handler Here
}
catch(IOException ex){
//Error Handler Here
} finally {
try{
if(br != null) br.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
Don't forget to import:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException
This should work as you expect. I assume that in the filename_in.txt you have only one line, otherwise you have to loop (I let you to do this as exercise):
public static void main(String[] args){
Scanner in = null;
PrintWriter writer = null;
try{
in = new Scanner(new FileReader("filename_in.txt"));
writer = new PrintWriter("filename_out.txt");
writer.println(printBackwards(in.nextLine()));
} catch (Exception e) {
e.printStackTrace();
}
finally {
in.close();
writer.close();
}
}
Hi, I am totally new in java.
This is my java code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
public class readw {
public static void main(String[] args) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\run\\input.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = lines.toArray();
}
}
When I am trying to compile it I got this type of error:
line 8: can not find symbol List (L)and ArrayList(A)
I am trying to get content of my text file and want to set in to as a array.
Add
import java.util.ArrayList;
import java.util.List;
yes its work now i want to see the array result. how?
With
System.out.println(lines);
You need to import all the classes you use.
import java.util.ArrayList;
import java.util.List;