Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.nio.file.NotDirectoryException;
- import java.util.*;
- import java.util.stream.Collectors;
- class ManageFiles {
- /**
- * Потребно е да ја имплементирате функцијата manage(String in, String out) која врши организација на текстуалните датотеки (*.dat) од именикот in според нивните привилегии на следниот начин:
- * <p>
- * доколку датотеката има привилегии за запишување тогаш таа треба да се премести во out именикот. При преместувањето, во конзола испечатете pomestuvam и апсолутното име на датотеката која се копира.
- * <p>
- * доколку датотеката нема привилегии за запишување тогаш нејзината содржина додадете ја на крај од датотеката writable-content.txt во resources именикот. При додавањето, во конзола испечатете dopisuvam и апсолутното име на датотеката. Сметајте дека овие датотеки може да бидат многу поголеми од физичката меморија на компјутерот.
- * <p>
- * доколку датотеката е скриена (hidden), тогаш избришете ја од in именикот, и во конзола испечатете zbunet sum и апсолутното име на датотеката.
- * <p>
- * Доколку in именикот не постои, испечатете на екран ne postoi.
- * <p>
- * Доколку out именикот веќе постои, избришете ја неговата содржина. Претпоставете дека во out именикот има само датотеки.
- */
- private static final String FROM_PATH = "Source_Folder";
- private static final String TO_PATH = "Destination_Folder";
- private static final String DATA_TXT = "Source_Folder\\data.txt";
- private static final String DEST_TXT = "Source_Folder\\dest.txt";
- private static final String RESOURCES = "Source_Folder\\resources\\writable-content.txt";
- private static void manage(String in, String out) throws IOException {
- File src = new File(in);
- File dest = new File(out);
- if (!src.exists()) throw new DirectoryNotFoundException("Src doesn't exist");
- if (!dest.isDirectory()) throw new DirectoryNotFoundException("Dest is Not a folder");
- if (dest.exists()) {
- deleteFolderContents(dest);
- } else {
- System.err.println("Dest doesn't exist!");
- if (dest.mkdir()) {
- System.out.println("Dest folder has been created");
- } else {
- throw new IOException("failed to make dest folder");
- }
- }
- File[] files = src.listFiles();
- assert files != null;
- files = Arrays.stream(files)
- .filter(file -> file.getName().endsWith(".dat") || file.getName().endsWith(".txt") || file.getName().endsWith(".java"))
- .toArray(File[]::new);
- for (File file : files) {
- if (file.isHidden()) {
- file.delete();
- System.out.println("I am confused: " + file.getAbsolutePath());
- } else {
- if (file.canWrite()) {
- file.renameTo(new File(dest, file.getName()));
- System.out.println("Moving: " + file.getAbsolutePath());
- } else {
- try (FileWriter writer = new FileWriter(new File(RESOURCES), true);
- BufferedReader reader = new BufferedReader(new FileReader(file))
- ) {
- String line = null;
- while ((line = reader.readLine()) != null) {
- writer.write(line + System.lineSeparator());
- }
- }
- System.out.println("Appending: " + file.getAbsolutePath());
- }
- }
- }
- }
- public static void main(String args[]) throws IOException {
- manage(FROM_PATH, TO_PATH);
- }
- private static void deleteFolderContents(File folder) {
- File[] files = folder.listFiles();
- assert files != null;
- Arrays.stream(files).forEach(File::delete);
- }
- class NotDirectoryException extends RuntimeException {
- public NotDirectoryException(String message) {
- super(message);
- }
- }
- static class DirectoryNotFoundException extends RuntimeException {
- public DirectoryNotFoundException(String message) {
- super(message);
- }
- }
- }
- class ExamIO {
- /**
- * 24-Mar-2018
- * First partial exam (Group 1)
- * <p>
- * Using Java I/O, implement the following methods of the ExamIO class:
- * <p>
- * (10 points) moveWritableTxtFiles(String from, String to)
- * <p>
- * Moves all files with the .txt extension which have writing permissions, from the from directory, to the to directory. If the from directory does not exist you should write "Does not exist", and if the to directory does not exist you need to create it.
- * (10 points) void deserializeData(String source, List<byte[]> data, long elementLength)
- * <p>
- * Reads the content of the source file, which contains a large amount of data, all in the same length in bytes, without a delimiter. Each of the data elements has a length of elementLength. The data read should be written in the data list, using data.add(readElement).
- * (Bonus 5 points) void invertLargeFile(String source, String destination)
- * <p>
- * The content of the source file is written in a reverse order (char by char) into the destination file. The source file content is too large and cannot be fitted into memory.
- */
- /**
- * (10 points)void copyLargeTxtFiles(String from, String to, long size)
- * <p>
- * Copies all .txt files which are larger than size (in bytes) from the from directory into the to directory. If the from directory does not exist, you should write "Does not exist" and if to does not exist you need to create it.
- * (10 points) void serializeData(String destination, List<byte[]> data)
- * <p>
- * The list of data in data is written into the destination file, without delimiters (as a continuous stream of bytes). All elements from data have the same length (same number of bytes).
- * (Bonus 5 points)byte[] deserializeDataAtPosition(String source, long position, long elementLength)
- * <p>
- * Reads and returns the data at the position position from the source file, which contains a large number of data, all with the same length in bytes, without delimiters. All data elements have the same elementLength length. You should not read the entire file in this method.
- */
- private static final String FROM_PATH = "Source_Folder";
- private static final String TO_PATH = "Destination_Folder";
- private static final String DATA_TXT = "Source_Folder\\data.txt";
- private static final String DEST_TXT = "Source_Folder\\dest.txt";
- private static final int BYTE_LENGTH = 1;
- private static final int ELEMENTS_LENGTH = 23;
- /**
- * Group 1
- */
- private static void moveWritableTxtFiles(String from, String to) {
- File source = new File(from);
- if (!source.exists()) {
- System.err.println("Source file doesn't exist!");
- return;
- }
- File dest = new File(to);
- if (!dest.exists()) {
- System.err.println("Destination file doesn't exist!");
- File folder = new File(".", dest.getName());
- if (folder.mkdir()) {
- System.out.println("Success");
- }
- dest = folder;
- }
- File[] files = source.listFiles();
- for (File file : files) {
- if (file.canWrite() && !file.isDirectory()) {
- if (file.getName().endsWith(".txt")) {
- file.renameTo(new File(dest, file.getName()));
- }
- }
- }
- }
- private static void deserializeData(String source, List<byte[]> data, long elementLength) throws IOException {
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(source);
- byte[] buffer = new byte[((int) elementLength)];
- while (fis.read(buffer) != -1) {
- data.add(buffer);
- buffer = new byte[(int) elementLength];
- }
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
- private static void invertLargeFile(String source, String destination) throws IOException {
- RandomAccessFile src = null;
- RandomAccessFile dest = null;
- try {
- src = new RandomAccessFile(source, "r");
- dest = new RandomAccessFile(destination, "rw");
- dest.setLength(0); // deletes the previous contents inside
- int numOfChars = 1;
- long pos = src.length();
- while (pos > 0) {
- src.seek(pos - numOfChars);
- dest.write(src.read());
- pos -= numOfChars;
- }
- } finally {
- if (src != null) {
- src.close();
- }
- if (dest != null) {
- dest.close();
- }
- }
- }
- /**
- * Group 2
- */
- private static void copyLargeTxtFiles(String from, String to, long size) throws IOException {
- File src = new File(from);
- File dest = new File(to);
- if (!src.exists()) throw new FileNotFoundException("Doesn't exist!");
- if (!src.isDirectory()) throw new NotDirectoryException("Not a folder!");
- if (!dest.exists()) {
- if (!dest.mkdir()) return; // it has failed
- //if it hasn't failed
- System.out.println("Created a new dest folder");
- }
- File[] files = src.listFiles();
- assert files != null;
- List<File> list = Arrays.stream(files)
- .filter(file -> !file.isDirectory())
- .filter(file -> file.getName().endsWith(".txt") || file.getName().endsWith(".java"))
- .filter(file -> file.length() > size)
- .collect(Collectors.toList());
- for (File file : list) {
- System.out.printf("Copying: %s\n", file.getAbsolutePath());
- String path = dest.getAbsolutePath() + "\\" + file.getName();
- File result = new File(path);
- try (
- BufferedReader reader = new BufferedReader(new FileReader(file));
- BufferedWriter writer = new BufferedWriter(new FileWriter(result))
- ) {
- String line = null;
- while ((line = reader.readLine()) != null) {
- writer.write(line + System.lineSeparator());
- }
- }
- System.out.printf("Copied: %s\n", result.getAbsolutePath());
- }
- }
- private static void serializeData(String destination, List<byte[]> data) throws FileNotFoundException {
- try (FileOutputStream fos = new FileOutputStream(new File(destination))) {
- for (byte[] bytes : data) {
- fos.write(bytes);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static byte[] deserializeDataAtPosition(String source, long position, long elementLength) throws IOException {
- if (position <= 0) {
- System.err.println("Position must be greater than 0");
- return null;
- }
- byte[] bytes = new byte[(int) elementLength];
- try (RandomAccessFile src = new RandomAccessFile(new File(source), "r")) {
- src.seek(BYTE_LENGTH * elementLength * (position - 1));
- for (int i = 0; i < elementLength; i++) {
- bytes[i] = src.readByte();
- }
- }
- return bytes;
- }
- public static void main(String args[]) throws IOException {
- File file = new File(FROM_PATH);
- Random random = new Random();
- //moveWritableTxtFiles(FROM_PATH, TO_PATH);
- //invertLargeFile(DATA_TXT, DEST_TXT);
- //copyLargeTxtFiles(FROM_PATH, TO_PATH, random.nextLong() % 541);
- /*
- List<byte[]> data = new ArrayList<>();
- for (int i = 0; i < 10; i++) {
- byte[] bytes = new byte[ELEMENTS_LENGTH];
- random.nextBytes(bytes);
- data.add(bytes);
- }
- serializeData(DEST_TXT, data);
- */
- /*byte[] bytes = deserializeDataAtPosition(DEST_TXT, random.nextInt(10) + 1, ELEMENTS_LENGTH);
- System.out.println(Arrays.toString(bytes));*/
- }
- private static void log(String msg) {
- System.out.println(msg);
- }
- }
- /**
- * Learned about:
- * String.indexOf() [has 4 versions]
- * FilenameFilter
- * op sys proc has just one pointer for reading a file
- */
- public class JavaIOMain {
- public static void listFiles() {
- String path = ".";
- File file = new File(path);
- List<String> list = new ArrayList<>(Arrays.asList(file.list(new DirFilter("xxx"))));
- System.out.println(list);
- }
- // interesting, mkdir in . but it shows on level above this source file.
- public static void folder() {
- File folder = new File(".", "Test-Folder");
- if (folder.mkdir()) {
- System.out.println("Success");
- }
- }
- public static void dataDotTxt() throws IOException {
- File current = new File(".");
- Optional<File> file = Arrays.stream(current.listFiles())
- .filter(f -> f.getName().contains("Test"))
- .findFirst();
- if (file.isPresent()) {
- File data = new File(file.get().getPath(), "data.txt");
- if (data.createNewFile()) {
- System.out.printf("Already made %s\n", data.getName());
- }
- PrintWriter pw = new PrintWriter(data, "UTF-8");
- pw.write("Hello, World!");
- pw.println("ama");
- pw.close();
- }
- }
- public static void createTxts(File current) throws IOException {
- for (int i = 0; i < 10; i++) {
- File fresh = new File(current.getPath(), String.format("%d.txt", i));
- if (fresh.createNewFile()) {
- System.out.printf("Created new File: %s\n", fresh.getName());
- }
- Random random = new Random();
- PrintWriter pw = new PrintWriter(fresh);
- for (int j = 0; j < 100; j++) {
- pw.println(random.nextFloat() * random.nextFloat() * random.nextFloat() * random.nextFloat() * Math.pow(10, 6));
- }
- pw.close();
- }
- }
- public static void main(String args[]) throws IOException {
- File current = new File("./Test-Folder");
- createTxts(current);
- File[] files = current.listFiles();
- float sumOfBytes = 0;
- int sumOfChars = 0;
- for (File file : files) {
- if (file.getName().indexOf(".txt", file.getName().length() - 1 - 4) != -1) {
- sumOfBytes += file.length();
- BufferedReader br = new BufferedReader(new FileReader(file));
- int length = br.lines().collect(Collectors.joining()).length();
- System.out.println(length);
- sumOfChars += length;
- }
- }
- System.out.printf("Average size of .txt files is %.2f KB\n", (sumOfBytes / Math.pow(1024, 1)));// 1 is for KB
- System.out.printf("Average number of chars of .txt files is %d\n", sumOfChars / files.length);
- }
- public static void createDirectory(File parent, String name) {
- File dir = new File(parent, name);
- if (dir.exists()) {
- System.err.println("The directory " + dir.getAbsolutePath()
- + " already exists!");
- } else {
- try {
- // mkdirs creates the directory together with the missing
- // parents
- boolean created = dir.mkdirs();
- if (created) {
- System.out.println(dir.getAbsolutePath() + " is created!");
- } else {
- System.out.println(dir.getAbsolutePath()
- + " is not created!");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- // example of call listFile(".", "");
- public static void listFile(String absolutePath, String indentation) {
- File file = new File(absolutePath);
- // Depth-First Search
- if (file.exists()) {
- File[] subfiles = file.listFiles();
- for (File f : subfiles) {
- // print the permissions in unix like format
- System.out.println(indentation + getPermissions(f) + "\t" + f.getName());
- // Recursively show the content of sub-directories
- if (f.isDirectory()) {
- listFile(f.getAbsolutePath(), indentation + "\t");
- }
- }
- }
- }
- public static String getPermissions(File f) {
- return String.format("%s%s%s", f.canRead() ? "r" : "-", f.canWrite() ? "w" : "-", f.canExecute() ? "x" : "-");
- }
- }
- class DirFilter implements FilenameFilter {
- String filter;
- public DirFilter(String filter) {
- this.filter = filter;
- }
- @Override
- public boolean accept(File dir, String name) {
- return new File(name).getName().contains(filter);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment