Как разделить ввод файла на 2 разных массива java

Как разделить текст ввода файла на 2 разных массива? Я хочу сделать массив n для имен и массив для номеров телефонов. Мне удалось ввести файл, но я попробовал все и, похоже, не смог разделить имена и числа, а затем поместить его в 2 разных массива. I m noob, пожалуйста, помогите

вот как выглядит файл phonebook.txt

Bin Arry,1110001111
Алекс Cadel,8943257000
Пох Caimon,3247129843
Диего Amezquita, 1001010000
Tai Mai Shu,7776665555
Yo Madow,1110002233
Caup Sul,5252521551
Этот парень,7776663333
Me And I,0009991221
Джастин тимьян,1113332222
Эй О,3939399339
Свободный человек,4533819911
Питер Пайпер,6480013966
Уильям Мюлок,9059671045

ниже мой код

   import java.io.*;
   import java.util.Scanner;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.IOException;
   import java.io.InputStreamReader;
   import java.io.BufferedReader;
   public class demos {
   public static void main(String[]  args){

    FileInputStream Phonebook;  
    DataInputStream In;
    int i = 0;

     String fileInput;  
      try  
      { 

            Phonebook = new FileInputStream("phonebook.txt"); 

            FileReader fr = new FileReader("phonebook.txt");
            BufferedReader br = new BufferedReader(fr);
            String buffer;
            String fulltext="";
            while ((buffer = br.readLine()) != null) {

                fulltext += buffer;

               // System.out.println(buffer);

                String names = buffer;
                char [] Y ; 
                Y = names.toCharArray();
                System.out.println(Y);

      }}
         catch (FileNotFoundException e)  
            { 
            System.out.println("Error - this file does not exist"); 
         }  
        catch (IOException e)   
        { 
            System.out.println("error=" + e.toString() ); 

         }

2 ответа

Для полноценного функционального (а не императивного) решения я предлагаю вам следующее:

public static void main(String[] args) throws IOException {
    Object[] names = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[0]).toArray();
    Object[] numbers = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[1]).toArray();


    System.out.println("names in the file are : ");
    Arrays.stream(names).forEach(System.out::println);
    System.out.println("numbers in the file are : ");
    Arrays.stream(numbers).forEach(System.out::println);
}

выход names in the file are : Bin Arry Alex Cadel Poh Caimon Diego Amezquita Tai Mai Shu Yo Madow Caup Sul This Guy Me And I Justin Thyme Hey Oh Free Man Peter Piper William Mulock numbers in the file are : 1110001111 8943257000 3247129843 1001010000 7776665555 1110002233 5252521551 7776663333 0009991221 1113332222 3939399339 4533819911 6480013966 9059671045

Как видите, функциональное программирование короткое и умное…. и легко, когда ты привык

Вы можете упростить его, если используете Java 8:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;

public class Test {
    static ArrayList<String> names = new ArrayList<String>();
    static ArrayList<String> numbers = new ArrayList<String>();

    /**
     * For each line, split it on the comma and send to splitNameAndNum()
     */
    public static void main(String[] args) throws IOException {
        Files.lines(new File("L:\\phonebook.txt").toPath())
        .forEach(l -> splitNameAndNum(l.split(",")));
    }

    /**
     * Accept an array of length 2 and put in the proper ArrayList
     */
    public static void splitNameAndNum(String[] arr) {
        names.add(arr[0]);
        numbers.add(arr[1]);
    }
}

А в Java 7:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.ArrayList;

public class Test {
    static ArrayList<String> names = new ArrayList<String>();
    static ArrayList<String> numbers = new ArrayList<String>();

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("L:\\phonebook.txt")));

        String line;

        while ((line = br.readLine()) != null) {
            splitNameAndNum(line.split(","));
        }
    }

    /**
     * Accept an array of length 2 and put in the proper ArrayList
     */
    public static void splitNameAndNum(String[] arr) {
        names.add(arr[0]);
        numbers.add(arr[1]);
    }
}
Другие вопросы по тегам