Facebook
From Unreliable Penguin, 6 Years ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 215
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package javaapplication5;
  7.  
  8. import java.io.*;
  9.  
  10. /**
  11.  * @author Daxo
  12.  */
  13. public class KopiujDane {
  14.  
  15.   public void copy(File source, File output, int linesToCopy) throws IOException {
  16.     validateLineNumber(source, linesToCopy);
  17.     validateFile(source);
  18.  
  19.     if (!output.exists()) {
  20.       System.out.println("Plik nie istnieje. Tworzę nowy.");
  21.       output.createNewFile();
  22.     }
  23.  
  24.     //Try with resources - używając tego nie trzeba zadeklarowanych streamów zamykać czyli omijamy 'finaly'
  25.     try(BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
  26.         FileOutputStream out = new FileOutputStream(output)) {
  27.  
  28.       for(int i = 0; i < linesToCopy; i++) {
  29.         out.write((in.readLine() + "\n").getBytes());
  30.       }
  31.  
  32.     }
  33.   }
  34.  
  35.   private void validateFile(final File source) {
  36.     if(!source.exists()) {
  37.       throw new IllegalArgumentException("Plik " + source.getAbsolutePath() + " nie istnieje.");
  38.     }
  39.   }
  40.  
  41.   private void validateLineNumber(final File source, final int linesToCopy) throws IOException {
  42.     if(linesToCopy > countLinesNumber(source)) {
  43.       throw new IllegalArgumentException("Liczba linii do skopiowania jest większa niż " +
  44.           "rzeczywista liczba linii w pliku");
  45.     }
  46.   }
  47.  
  48.   private int countLinesNumber(File file) throws IOException {
  49.     int lines = 0;
  50.     try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
  51.       while (reader.readLine() != null) {
  52.         lines++;
  53.       }
  54.     }
  55.     return lines;
  56.   }
  57. }
  58.  
  59.