1

I have a text file like this :

abc def jhi
klm nop qrs
tuv wxy zzz

I want to have a string array like :

String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"}

I've tried :

try
    {
        FileInputStream fstream_school = new FileInputStream("text1.txt");
        DataInputStream data_input = new DataInputStream(fstream_school);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
        String str_line;
        while ((str_line = buffer.readLine()) != null)
        {
            str_line = str_line.trim();
            if ((str_line.length()!=0)) 
            {
                String[] itemsSchool = str_line.split("\t");
            }
        }
    }
catch (Exception e)  
    {
     // Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

Anyone help me please.... All answer would be appreciated...

Edward Sullen
  • 157
  • 1
  • 5
  • 18

7 Answers7

11

If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method:

List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
assylias
  • 321,522
  • 82
  • 660
  • 783
2

Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

This is my code to generate random emails creating an array from a text file.

import java.io.*;

public class Generator {
    public static void main(String[]args){

        try {

            long start = System.currentTimeMillis();
            String[] firstNames = new String[4945];
            String[] lastNames = new String[88799];
            String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
            String firstName;
            String lastName;
            int counter0 = 0;
            int counter1 = 0;
            int generate = 1000000;//number of emails to generate

            BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
            BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
            PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));


            while ((firstName = firstReader.readLine()) != null) {
                firstName = firstName.toLowerCase();
                firstNames[counter0] = firstName;
                counter0++;
            }
            while((lastName= lastReader.readLine()) !=null){
                lastName = lastName.toLowerCase();
                lastNames[counter1]=lastName;
                counter1++;
            }

            for(int i=0;i<generate;i++) {
                write.println(firstNames[(int)(Math.random()*4945)]
                        +'.'+lastNames[(int)(Math.random()*88799)]+'@'+emailProvider[(int)(Math.random()*emailProvider.length)]);
            }
            write.close();
            long end = System.currentTimeMillis();

            long time = end-start;

            System.out.println("it took "+time+"ms to generate "+generate+" unique emails");

        }
        catch(IOException ex){
            System.out.println("Wrong input");
        }
    }
}
Stephan Hogenboom
  • 1,543
  • 2
  • 17
  • 29
kryzystof
  • 190
  • 2
  • 13
1

Based on your input you are almost there. You missed the point in your loop where to keep each line read from the file. As you don't a priori know the total lines in the file, use a collection (dynamically allocated size) to get all the contents and then convert it to an array of String (as this is your desired output).

Something like this:

    String[] arr= null;
    List<String> itemsSchool = new ArrayList<String>();

    try 
    { 
        FileInputStream fstream_school = new FileInputStream("text1.txt"); 
        DataInputStream data_input = new DataInputStream(fstream_school); 
        BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input)); 
        String str_line; 

        while ((str_line = buffer.readLine()) != null) 
        { 
            str_line = str_line.trim(); 
            if ((str_line.length()!=0))  
            { 
                itemsSchool.add(str_line);
            } 
        }

        arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]);
    }

Then the output (arr) would be:

{"abc def jhi","klm nop qrs","tuv wxy zzz"} 

This is not the optimal solution. Other more clever answers have already be given. This is only a solution for your current approach.

pankar
  • 1,623
  • 1
  • 11
  • 21
  • Thanks, I think it's work but in the LogCat, show that : Error : /text1.txt: open failed: ENOENT ( No such file or directory) – Edward Sullen Oct 12 '12 at 11:57
  • You should have your `text1.txt` input file in your current directory (as you have it in your question) otherwise you need to provide the path along with the filename – pankar Oct 12 '12 at 12:02
  • yeah, I put it in the same folder. Sorry, I forgot mention that i'm developing android app. Will it be the same path as normal Java App ? – Edward Sullen Oct 12 '12 at 12:10
  • Yes in the same folder, but it's a good practice not to mess your configuration files with your source code. You'd better create a folder and place it there – pankar Oct 12 '12 at 12:32
  • I still found error. some tutorial mention about method getFileDir() of android in order to go the path of a file. when I use it, in LogCat ask me to put the file in /data/data/ – Edward Sullen Oct 12 '12 at 22:34
0

You can read file line by line using some input stream or scanner and than store that line in String Array.. A sample code will be..

 File file = new File("data.txt");

        try {
            //
            // Create a new Scanner object which will read the data 
            // from the file passed in. To check if there are more 
            // line to read from it we check by calling the 
            // scanner.hasNextLine() method. We then read line one 
            // by one till all line is read.
            //
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                //store this line to string [] here
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
Amit
  • 13,134
  • 17
  • 77
  • 148
0
    Scanner scanner = new Scanner(InputStream);//Get File Input stream here
    StringBuilder builder = new StringBuilder();
    while (scanner.hasNextLine()) {
        builder.append(scanner.nextLine());
        builder.append(" ");//Additional empty space needs to be added
    }
    String strings[] = builder.toString().split(" ");
    System.out.println(Arrays.toString(strings));

Output :

   [abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz]

You can read more about scanner here

Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
0

You can use the readLine function to read the lines in a file and add it to the array.

Example :

  File file = new File("abc.txt");
  FileInputStream fin = new FileInputStream(file);
  BufferedReader reader = new BufferedReader(fin);

  List<String> list = new ArrayList<String>();
  while((String str = reader.readLine())!=null){
     list.add(str);
  }

  //convert the list to String array
  String[] strArr = Arrays.toArray(list);

The above array contains your required output.

karfau
  • 638
  • 4
  • 17
Gunjan Shah
  • 5,088
  • 16
  • 53
  • 72