Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javarush.test.level19.lesson05.task03;
- /* Выделяем числа
- Считать с консоли 2 имени файла.
- Вывести во второй файл все числа, которые есть в первом файле.
- Числа выводить через пробел.
- Закрыть потоки. Не использовать try-with-resources
- Пример тела файла:
- 12 text var2 14 8v 1
- Результат:
- 12 14 1
- */
- import java.io.*;
- import java.util.ArrayList;
- import java.util.Arrays;
- public class Solution {
- public static void main(String[] args) {
- BufferedReader reader = null;
- try
- {
- reader = new BufferedReader(new InputStreamReader(System.in));
- String fileName = reader.readLine();
- String outFile = reader.readLine();
- reader.close();
- writeToFile(outFile,getNums(fileName));
- reader.close();
- }
- catch (Exception e) {}
- finally
- {
- if (reader!=null) {
- try
- {
- reader.close();
- }
- catch (IOException e) {}
- }
- }
- }
- public static ArrayList <String> getNums (String sourceFile){
- ArrayList<String>myNums = new ArrayList<String>();
- BufferedReader readeFile = null;
- try
- {
- readeFile = new BufferedReader(new FileReader(sourceFile));
- String tmp="";
- while ((tmp=readeFile.readLine())!=null){
- //tmp=tmp.replaceAll("[^0-9\\s]", " ");
- String[]strings = tmp.split(" ");
- for (String s : strings){
- if (isNumeric(s)) {
- myNums.add(s);
- }
- }
- }
- readeFile.close();
- myNums.removeAll(Arrays.asList("", null));
- }
- catch (Exception e) {}
- finally
- {
- if (readeFile!=null) {
- try
- {
- readeFile.close();
- }
- catch (IOException e) {}
- }
- }
- return myNums;
- }
- public static void writeToFile (String outPut, ArrayList<String>nums) {
- FileWriter fileWriter = null;
- try
- {
- fileWriter = new FileWriter(outPut);
- for (String s : nums) {
- fileWriter.write((Integer.parseInt(s)+" "));
- }
- fileWriter.close();
- }
- catch (Exception e) {}
- finally
- {
- if (fileWriter!=null) {
- try
- {
- fileWriter.close();
- }
- catch (IOException e) {}
- }
- }
- }
- public static boolean isNumeric(String str)
- {
- try
- {
- double d = Integer.parseInt(str);
- }
- catch(NumberFormatException nfe)
- {
- return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement