Sorry if my code is a little messy, hope the notes make it easier to read
package com.codegym.task.task18.task1823;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
/*
Threads and bytes
*/
public class Solution {
public static Map<String, Integer> resultMap = new HashMap<String, Integer>();
public static void main(String[] args) throws IOException, InterruptedException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
String fileName = reader.readLine();
if (fileName.equals("exit"))
break;
ReadThread readThread = new ReadThread(fileName);
readThread.start();
readThread.join();
resultMap.put(fileName, readThread.getFrequentByteAsInteger());
}
}
public static class ReadThread extends Thread {
private String fileName;
private Integer frequentByteAsInteger;
public ReadThread(String fileName) throws IOException {
// Implement constructor body
this.fileName = fileName;
}
// Implement file reading here
@Override
public void run() {
//create InputStream for file and read to buffer
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(this.fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buffer = new byte[0];
try {
buffer = new byte[fileInputStream.available()];
} catch (IOException e) {
e.printStackTrace();
}
while (true){
try {
if (!(fileInputStream.available()>0)) break;
} catch (IOException e) {
e.printStackTrace();
}
try {
fileInputStream.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
//copy to Byte Array
Byte[] bufferByte = new Byte[buffer.length];
int i = 0;
for (byte b : buffer)
bufferByte[i++] = b;
//copy to ArrayList and find most frequent element
ArrayList<Byte> bytes = (ArrayList<Byte>) Arrays.asList(bufferByte);
int frequency =0;
Byte frequentByte =0;
for (int x = 0; x<bytes.size();x++) {
if (Collections.frequency(bytes, bytes.get(x)) > frequency) {
frequency = Collections.frequency(bytes, bytes.get(x));
frequentByte = bytes.get(x);
}
}
this.frequentByteAsInteger = Integer.valueOf(frequentByte);
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Integer getFrequentByteAsInteger(){
return this.frequentByteAsInteger;
}
}
}