Advertisement
jaVer404

level19.lesson05.task03(done)

Feb 19th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.29 KB | None | 0 0
  1. package com.javarush.test.level19.lesson05.task03;
  2.  
  3. /* Выделяем числа
  4. Считать с консоли 2 имени файла.
  5. Вывести во второй файл все числа, которые есть в первом файле.
  6. Числа выводить через пробел.
  7. Закрыть потоки. Не использовать try-with-resources
  8.  
  9. Пример тела файла:
  10. 12 text var2 14 8v 1
  11.  
  12. Результат:
  13. 12 14 1
  14. */
  15.  
  16. import java.io.*;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19.  
  20. public class Solution {
  21.     public static void main(String[] args) throws IOException  {
  22.  
  23.             BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  24.             String fileName = reader.readLine();
  25.             String outFile = reader.readLine();
  26.             writeToFile(outFile,getNums(fileName));
  27.             reader.close();
  28.     }
  29.  
  30.     public static ArrayList <String> getNums (String sourceFile){
  31.         ArrayList<String>myNums = null;
  32.         try
  33.         {
  34.             myNums = new ArrayList<String>();
  35.             BufferedReader readeFile = new BufferedReader(new FileReader(sourceFile));
  36.             String tmp="";
  37.             while ((tmp=readeFile.readLine())!=null){
  38.                 String[]strings = tmp.split(" ");
  39.                 for (String s : strings){
  40.                     if (isNumeric(s)) {
  41.                         myNums.add(s);
  42.                     }
  43.                 }
  44.             }
  45.             readeFile.close();
  46.             myNums.removeAll(Arrays.asList("", null));
  47.         }
  48.         catch (IOException e) {}
  49.         return myNums;
  50.     }
  51.  
  52.  
  53.     public static void writeToFile (String outPut, ArrayList<String>nums) {
  54.         try
  55.         {
  56.             FileWriter fileWriter = new FileWriter(outPut);
  57.             int sizeOf = nums.size();
  58.             for (int i = 0; i<sizeOf;i++) {
  59.                 fileWriter.write(nums.get(i)+" ");
  60.             }
  61.             fileWriter.close();
  62.         }
  63.         catch (IOException e) {}
  64.     }
  65.  
  66.     public static boolean isNumeric(String str)
  67.     {
  68.         try
  69.         {
  70.             int d = Integer.parseInt(str);
  71.         }
  72.         catch(NumberFormatException nfe)
  73.         {
  74.             return false;
  75.         }
  76.         return true;
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement