Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Task 1 Problem 1 (1 / 1)
- Write a Java program which will show the average size of the all .txt files which are part of the directory
- denoted as a command line argument.
- Note: Use the File class to access the content of the directory.
- Solution: The HW01_1.java file from your solution should be placed here, using copy-paste.
- */
- import java.io.File;
- import java.util.Arrays;
- public class HW01_1 {
- public static void main(String[] args) {
- //Example path: C:\Users\Woody's Laptop\Desktop
- if (args.length == 0){
- System.err.println("ERROR: No directory specified!");
- return;
- }
- File dir = new File(args[0]);
- if (!dir.exists() || !dir.isDirectory()){
- System.err.println("ERROR: There is no such directory or the specified file is not a directory!");
- return;
- }
- File[] files = dir.listFiles((dir1, name) -> name.contains(".txt"));
- if(files == null) {
- System.err.println("ERROR: There are no .txt files in this directory!");
- return;
- }
- // listFiles has parameter FilenameFilter interface (can be lambda)
- // Lists all .txt files
- double sum = Arrays.stream(files).mapToLong(File::length).sum();
- System.out.println("Total size of the .txt files is: " + sum + " bytes.\nAverage size of the .txt files is: " + sum /files.length + " bytes.");
- }
- }
- /*
- Task 2 Problem 2 (1 / 1)
- Write a Java program which will use I/O streams to read the content of the file source.txt, and then
- write out its content in a reverse order to the empty file destination.txt. The read and write should be
- done using streams which work byte-by-byte.
- Example:
- source.txt destination.txt
- Operating Systems smetsyS gnitarepO
- Note: You should create these two files yourself and fill izvor.txt with some arbitrary content.
- Solution: The HW01_2.java file should be placed here, using copy-paste.
- */
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- public class HW01_2 {
- public static void main(String[] args) {
- File source = new File("source.txt");
- File dest = new File("destination.txt");
- if(!source.exists()) createAndFill(source, true);
- if(!dest.exists()) createAndFill(dest, false);
- copyReverse(source.getAbsolutePath(), dest.getAbsolutePath());
- System.out.println("Successful execution!");
- }
- private static void createAndFill(File f, boolean fill) {
- try {
- if(f.createNewFile() && fill) {
- FileWriter fw = new FileWriter(f);
- fw.write("Operating Systems");
- fw.flush();
- fw.close();
- System.out.println("Files are successfully created!");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static void copyReverse(String from, String to) {
- try {
- RandomAccessFile source = new RandomAccessFile(from, "rw");
- RandomAccessFile dest = new RandomAccessFile(to, "rw");
- long i = source.length()-1;
- while(i >= 0)
- {
- source.seek(i);
- dest.write(source.read()); // write and read 1 byte
- i--;
- // Prasaj kako bi se resilo so FileOutputStream najoptimalno so byte po byte?!?!
- }
- source.close();
- dest.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /*
- Task 3 Problem 3 (1 / 1)
- Write a Java program which will use I/O streams to read the content of the file source.txt,
- and then write out its content in a reverse order to the empty file destination.txt.
- The read and write should be done using buffered streams.
- Example:
- source.txt destination.txt
- Operating Systems smetsyS gnitarepO
- Note: You should create these two files yourself and fill izvor.txt with some arbitrary content.
- Solution: The HW01_3.java file should be placed here, using copy-paste.
- */
- import java.io.*;
- public class HW01_3 {
- public static void main(String[] args) {
- File source = new File("source.txt");
- File dest = new File("destination.txt");
- if(!source.exists()) createAndFill(source, true);
- if(!dest.exists()) createAndFill(dest, false);
- copyReverse(source.getAbsolutePath(), dest.getAbsolutePath());
- System.out.println("Successful execution!");
- }
- private static void createAndFill(File f, boolean fill) {
- try {
- if(f.createNewFile() && fill) {
- FileWriter fw = new FileWriter(f);
- fw.write("Operating Systems");
- fw.flush();
- fw.close();
- System.out.println("Files are successfully created!");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static void copyReverse(String from, String to) {
- try {
- BufferedReader br = new BufferedReader(new FileReader(from));
- BufferedWriter bw = new BufferedWriter(new FileWriter(to));
- StringBuilder sb;
- String str;
- while ((str = br.readLine()) != null){
- sb = new StringBuilder(str);
- sb.reverse();
- bw.write(sb+"\n");
- }
- br.close();
- bw.flush();
- bw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /*Task 4 Problem 4 (2 / 2)
- One e-learning system generates grade reports in a CSV (Comma Separated Values) format. Write a Java program which
- will print out the average grade of each student from the file results.csv (see the example below), and the average
- grade of each course (given in the first line of the file). The program should work with any number of lines in
- an input CSV file.
- Student,SP,OOP,CAO
- 11234,8,9,8
- 13456,6,7,9
- 11111,7,8,8
- 10123,10,10,10
- Bonus: For better readability of the file, transform the input file results.csv into a TSV (Tab Separated Values)
- formatted file, and save it as results.tsv.
- Solution: Place the HW01_4.java file from your solution here, using copy-paste.
- */
- import java.io.*;
- public class HW01_4 {
- public static void main(String[] args) throws IOException {
- try {
- //Student,SP,OOP,CAO
- //11234,8,9,8
- //13456,6,7,9
- //11111,7,8,8
- //10123,10,10,10
- BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("results.csv")));
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("results.tsv")));
- //Bonus part
- String line = br.readLine();
- String[] parts = line.split(",");
- bw.write(line.replace(",", "\t")+"\n");
- int students = 0;
- int[] courseSum = new int[parts.length];
- while((line = br.readLine()) != null){
- parts = line.split(",");
- int studentSum = 0;
- students++;
- for (int i=1; i<parts.length; i++){
- studentSum += Integer.parseInt(parts[i]);
- courseSum[i] += Integer.parseInt(parts[i]);
- }
- System.out.println("The student with the index " + parts[0] + " has average grade: " + (studentSum*1.0/(parts.length-1)));
- bw.write(line.replace(",", "\t")+"\n");
- }
- for (int i=1; i<parts.length; i++)
- System.out.println("The subject " + parts[i] + " has average grade: " + (courseSum[i]*1.0 / students));
- br.close();
- bw.flush();
- bw.close();
- } catch (FileNotFoundException e) {
- System.out.println("No such file found!");
- }
- }
- }
- /*
- Task 5 - Java Networking Problem 5 (0 / 0)
- We need to simulate a TCP/IP connection and communication between a client and a server.
- 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.
- The messages that TCPClient needs to send are given bellow, and must be sent in the exact same order.
- 1.25 (Double) 123584124 (Long) true (boolean) "UTF String" (String)
- TCPServer expects the same sequence of messages, and it prints every message it receives.
- _Hint_: Use the appropriate streams to read/write primitive data types*
- */
- /*
- SERVER
- */
- import java.io.BufferedReader;
- import java.io.DataInputStream;
- import java.io.InputStreamReader;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class HW01_5_TCPServer {
- private ServerSocket server;
- private HW01_5_TCPServer() throws Exception {
- this.server = new ServerSocket(9876);
- }
- private void listen() throws Exception {
- Socket client = this.server.accept();
- String clientAddress = client.getInetAddress().getHostAddress();
- System.out.println("\r\nNew connection from " + clientAddress);
- DataInputStream in = new DataInputStream(client.getInputStream());
- System.out.println("\rMessage from " + clientAddress + ": " + in.readDouble());
- System.out.println("\rMessage from " + clientAddress + ": " + in.readLong());
- System.out.println("\rMessage from " + clientAddress + ": " + in.readBoolean());
- System.out.println("\rMessage from " + clientAddress + ": " + in.readUTF());
- }
- public static void main(String[] args) throws Exception {
- HW01_5_TCPServer app = new HW01_5_TCPServer();
- System.out.println("\r\nRunning Server: " +
- "Host=" + app.server.getInetAddress() +
- " Port=" + app.server.getLocalPort());
- app.listen();
- }
- }
- /*
- CLIENT
- */
- import java.io.*;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.net.SocketException;
- import java.util.Scanner;
- public class HW01_5_TCPClient {
- private Socket socket;
- private Scanner scanner;
- private HW01_5_TCPClient(InetAddress serverAddress, int serverPort) throws Exception {
- this.socket = new Socket(serverAddress, serverPort);
- this.scanner = new Scanner(System.in);
- }
- private void start() throws IOException {
- while(true) {
- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(this.socket.getOutputStream()));
- out.writeDouble(1.25);
- out.writeLong(123584124L);
- out.writeBoolean(true);
- out.writeUTF("UTF String");
- out.flush();
- this.socket.close();
- }
- }
- public static void main(String[] args) throws Exception {
- HW01_5_TCPClient client = new HW01_5_TCPClient(
- InetAddress.getByName("localhost"), 9876);
- System.out.println("\r\nConnected to Server: " + client.socket.getInetAddress());
- try {
- client.start();
- } catch(SocketException se) {
- System.out.println("Message is successfully sent and the connection is closed!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement