Advertisement
jaVer404

level19.lesson05.task03(not tested 4)

Feb 19th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.32 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.         FileWriter fileWriter = null;
  55.         try
  56.         {
  57.             fileWriter = new FileWriter(outPut);
  58.             int sizeOf = nums.size();
  59.             for (int i = 0; i<sizeOf;i++) {
  60.                 fileWriter.write(nums.get(i)+" ");
  61.             }
  62.             fileWriter.close();
  63.         }
  64.         catch (IOException e) {}
  65.     }
  66.  
  67.     public static boolean isNumeric(String str)
  68.     {
  69.         try
  70.         {
  71.             int d = Integer.parseInt(str);
  72.         }
  73.         catch(NumberFormatException nfe)
  74.         {
  75.             return false;
  76.         }
  77.         return true;
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement