SHARE
TWEET

(Java) OS: Lab 1 - ОС: Лаб 1

StefanTodorovski Mar 21st, 2019 (edited) 125 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Task 1 Problem 1 (1 / 1)
  3. Write a Java program which will show the average size of the all .txt files which are part of the directory
  4. denoted as a command line argument.
  5.  
  6. Note: Use the File class to access the content of the directory.
  7. Solution: The HW01_1.java file from your solution should be placed here, using copy-paste.
  8. */
  9.  
  10. import java.io.File;
  11. import java.util.Arrays;
  12.  
  13. public class HW01_1 {
  14.     public static void main(String[] args) {
  15.         //Example path: C:\Users\Woody's Laptop\Desktop
  16.         if (args.length == 0){
  17.             System.err.println("ERROR: No directory specified!");
  18.             return;
  19.         }
  20.         File dir = new File(args[0]);
  21.  
  22.         if (!dir.exists() || !dir.isDirectory()){
  23.             System.err.println("ERROR: There is no such directory or the specified file is not a directory!");
  24.             return;
  25.         }
  26.  
  27.         File[] files = dir.listFiles((dir1, name) -> name.contains(".txt"));
  28.         if(files == null) {
  29.             System.err.println("ERROR: There are no .txt files in this directory!");
  30.             return;
  31.         }
  32.         // listFiles has parameter FilenameFilter interface (can be lambda)
  33.         // Lists all .txt files
  34.  
  35.         double sum = Arrays.stream(files).mapToLong(File::length).sum();
  36.         System.out.println("Total size of the .txt files is: " + sum + " bytes.\nAverage size of the .txt files is: " + sum /files.length + " bytes.");
  37.     }
  38. }
  39.  
  40.  
  41.  
  42. /*
  43. Task 2 Problem 2 (1 / 1)
  44. Write a Java program which will use I/O streams to read the content of the file source.txt, and then
  45. write out its content in a reverse order to the empty file destination.txt. The read and write should be
  46. done using streams which work byte-by-byte.
  47.  
  48. Example:
  49. source.txt                  destination.txt
  50. Operating Systems           smetsyS gnitarepO
  51.  
  52. Note: You should create these two files yourself and fill izvor.txt with some arbitrary content.
  53. Solution: The HW01_2.java file should be placed here, using copy-paste.
  54.  */
  55.  
  56. import java.io.File;
  57. import java.io.FileWriter;
  58. import java.io.IOException;
  59. import java.io.RandomAccessFile;
  60.  
  61. public class HW01_2 {
  62.     public static void main(String[] args) {
  63.         File source = new File("source.txt");
  64.         File dest = new File("destination.txt");
  65.         if(!source.exists()) createAndFill(source, true);
  66.         if(!dest.exists()) createAndFill(dest, false);
  67.  
  68.         copyReverse(source.getAbsolutePath(), dest.getAbsolutePath());
  69.  
  70.         System.out.println("Successful execution!");
  71.     }
  72.  
  73.     private static void createAndFill(File f, boolean fill) {
  74.         try {
  75.             if(f.createNewFile() && fill) {
  76.                 FileWriter fw = new FileWriter(f);
  77.                 fw.write("Operating Systems");
  78.                 fw.flush();
  79.                 fw.close();
  80.                 System.out.println("Files are successfully created!");
  81.             }
  82.         } catch (IOException e) {
  83.             e.printStackTrace();
  84.         }
  85.     }
  86.  
  87.     private static void copyReverse(String from, String to) {
  88.         try {
  89.             RandomAccessFile source = new RandomAccessFile(from, "rw");
  90.             RandomAccessFile dest = new RandomAccessFile(to, "rw");
  91.  
  92.             long i = source.length()-1;
  93.             while(i >= 0)
  94.             {
  95.                 source.seek(i);
  96.                 dest.write(source.read()); // write and read 1 byte
  97.                 i--;
  98.                 // Prasaj kako bi se resilo so FileOutputStream najoptimalno so byte po byte?!?!
  99.             }
  100.             source.close();
  101.             dest.close();
  102.         } catch (IOException e) {
  103.             e.printStackTrace();
  104.         }
  105.     }
  106. }
  107.  
  108.  
  109.  
  110. /*
  111. Task 3 Problem 3 (1 / 1)
  112. Write a Java program which will use I/O streams to read the content of the file source.txt,
  113. and then write out its content in a reverse order to the empty file destination.txt.
  114. The read and write should be done using buffered streams.
  115.  
  116. Example:
  117. source.txt                  destination.txt
  118. Operating Systems           smetsyS gnitarepO
  119.  
  120. Note: You should create these two files yourself and fill izvor.txt with some arbitrary content.
  121. Solution: The HW01_3.java file should be placed here, using copy-paste.
  122.  */
  123.  
  124. import java.io.*;
  125.  
  126. public class HW01_3 {
  127.     public static void main(String[] args) {
  128.         File source = new File("source.txt");
  129.         File dest = new File("destination.txt");
  130.         if(!source.exists()) createAndFill(source, true);
  131.         if(!dest.exists()) createAndFill(dest, false);
  132.  
  133.         copyReverse(source.getAbsolutePath(), dest.getAbsolutePath());
  134.  
  135.         System.out.println("Successful execution!");
  136.     }
  137.  
  138.     private static void createAndFill(File f, boolean fill) {
  139.         try {
  140.             if(f.createNewFile() && fill) {
  141.                 FileWriter fw = new FileWriter(f);
  142.                 fw.write("Operating Systems");
  143.                 fw.flush();
  144.                 fw.close();
  145.                 System.out.println("Files are successfully created!");
  146.             }
  147.         } catch (IOException e) {
  148.             e.printStackTrace();
  149.         }
  150.     }
  151.  
  152.     private static void copyReverse(String from, String to) {
  153.         try {
  154.             BufferedReader br = new BufferedReader(new FileReader(from));
  155.             BufferedWriter bw = new BufferedWriter(new FileWriter(to));
  156.  
  157.             StringBuilder sb;
  158.             String str;
  159.  
  160.             while ((str = br.readLine()) != null){
  161.                 sb = new StringBuilder(str);
  162.                 sb.reverse();
  163.                 bw.write(sb+"\n");
  164.             }
  165.  
  166.             br.close();
  167.             bw.flush();
  168.             bw.close();
  169.         } catch (IOException e) {
  170.             e.printStackTrace();
  171.         }
  172.     }
  173. }
  174.  
  175.  
  176.  
  177. /*Task 4 Problem 4 (2 / 2)
  178. One e-learning system generates grade reports in a CSV (Comma Separated Values) format. Write a Java program which
  179. will print out the average grade of each student from the file results.csv (see the example below), and the average
  180. grade of each course (given in the first line of the file). The program should work with any number of lines in
  181. an input CSV file.
  182.  
  183. Student,SP,OOP,CAO
  184. 11234,8,9,8
  185. 13456,6,7,9
  186. 11111,7,8,8
  187. 10123,10,10,10
  188.  
  189. Bonus: For better readability of the file, transform the input file results.csv into a TSV (Tab Separated Values)
  190. formatted file, and save it as results.tsv.
  191.  
  192. Solution: Place the HW01_4.java file from your solution here, using copy-paste.
  193. */
  194.  
  195. import java.io.*;
  196.  
  197. public class HW01_4 {
  198.     public static void main(String[] args) throws IOException {
  199.         try {
  200.             //Student,SP,OOP,CAO
  201.             //11234,8,9,8
  202.             //13456,6,7,9
  203.             //11111,7,8,8
  204.             //10123,10,10,10
  205.  
  206.             BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("results.csv")));
  207.             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("results.tsv")));
  208.  
  209.             //Bonus part
  210.             String line = br.readLine();
  211.             String[] parts = line.split(",");
  212.             bw.write(line.replace(",", "\t")+"\n");
  213.  
  214.             int students = 0;
  215.             int[] courseSum = new int[parts.length];
  216.  
  217.             while((line = br.readLine()) != null){
  218.                 parts = line.split(",");
  219.  
  220.                 int studentSum = 0;
  221.                 students++;
  222.  
  223.                 for (int i=1; i<parts.length; i++){
  224.                     studentSum += Integer.parseInt(parts[i]);
  225.                     courseSum[i] += Integer.parseInt(parts[i]);
  226.                 }
  227.  
  228.                 System.out.println("The student with the index " + parts[0] + " has average grade: " + (studentSum*1.0/(parts.length-1)));
  229.                 bw.write(line.replace(",", "\t")+"\n");
  230.             }
  231.  
  232.             for (int i=1; i<parts.length; i++)
  233.                 System.out.println("The subject " + parts[i] + " has average grade: " + (courseSum[i]*1.0 / students));
  234.  
  235.             br.close();
  236.             bw.flush();
  237.             bw.close();
  238.         } catch (FileNotFoundException e) {
  239.             System.out.println("No such file found!");
  240.         }
  241.     }
  242. }
  243.  
  244.  
  245.  
  246. /*
  247. Task 5 - Java Networking Problem 5 (0 / 0)
  248.  
  249. We need to simulate a TCP/IP connection and communication between a client and a server.
  250. For that purpose, you need to create two applications, TCPServer, which will run on port 9876 and will act as a TCP Server, and TCP Client which will connect to the server and send messages to it.
  251. The messages that TCPClient needs to send are given bellow, and must be sent in the exact same order.
  252. 1.25 (Double) 123584124 (Long) true (boolean) "UTF String" (String)
  253. TCPServer expects the same sequence of messages, and it prints every message it receives.
  254.  
  255. _Hint_: Use the appropriate streams to read/write primitive data types*
  256.  */
  257.  
  258. /*
  259.  
  260. SERVER
  261.  
  262. */
  263.  
  264. import java.io.BufferedReader;
  265. import java.io.DataInputStream;
  266. import java.io.InputStreamReader;
  267. import java.net.ServerSocket;
  268. import java.net.Socket;
  269.  
  270. public class HW01_5_TCPServer {
  271.  
  272.     private ServerSocket server;
  273.     private HW01_5_TCPServer() throws Exception {
  274.         this.server = new ServerSocket(9876);
  275.     }
  276.  
  277.     private void listen() throws Exception {
  278.         Socket client = this.server.accept();
  279.         String clientAddress = client.getInetAddress().getHostAddress();
  280.         System.out.println("\r\nNew connection from " + clientAddress);
  281.  
  282.         DataInputStream in = new DataInputStream(client.getInputStream());
  283.  
  284.         System.out.println("\rMessage from " + clientAddress + ": " + in.readDouble());
  285.         System.out.println("\rMessage from " + clientAddress + ": " + in.readLong());
  286.         System.out.println("\rMessage from " + clientAddress + ": " + in.readBoolean());
  287.         System.out.println("\rMessage from " + clientAddress + ": " + in.readUTF());
  288.     }
  289.  
  290.     public static void main(String[] args) throws Exception {
  291.         HW01_5_TCPServer app = new HW01_5_TCPServer();
  292.         System.out.println("\r\nRunning Server: " +
  293.                 "Host=" + app.server.getInetAddress() +
  294.                 " Port=" + app.server.getLocalPort());
  295.  
  296.         app.listen();
  297.     }
  298. }
  299.  
  300. /*
  301.  
  302. CLIENT
  303.  
  304. */
  305.  
  306. import java.io.*;
  307. import java.net.InetAddress;
  308. import java.net.Socket;
  309. import java.net.SocketException;
  310. import java.util.Scanner;
  311.  
  312. public class HW01_5_TCPClient {
  313.     private Socket socket;
  314.     private Scanner scanner;
  315.  
  316.     private HW01_5_TCPClient(InetAddress serverAddress, int serverPort) throws Exception {
  317.         this.socket = new Socket(serverAddress, serverPort);
  318.         this.scanner = new Scanner(System.in);
  319.     }
  320.  
  321.     private void start() throws IOException {
  322.         while(true) {
  323.             DataOutputStream out = new DataOutputStream(new BufferedOutputStream(this.socket.getOutputStream()));
  324.             out.writeDouble(1.25);
  325.             out.writeLong(123584124L);
  326.             out.writeBoolean(true);
  327.             out.writeUTF("UTF String");
  328.             out.flush();
  329.             this.socket.close();
  330.         }
  331.     }
  332.  
  333.     public static void main(String[] args) throws Exception {
  334.         HW01_5_TCPClient client = new HW01_5_TCPClient(
  335.                 InetAddress.getByName("localhost"), 9876);
  336.         System.out.println("\r\nConnected to Server: " + client.socket.getInetAddress());
  337.         try {
  338.             client.start();
  339.         } catch(SocketException se) {
  340.             System.out.println("Message is successfully sent and the connection is closed!");
  341.         }
  342.     }
  343. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top