skip to Main Content

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?

3

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search