1. import java.io.*;
  2. import java.nio.file.*;
  3. public class BinaryFileNormalizer {
  4. /**
  5. * Normalizes the data of a binary file by converting it to a byte array
  6. * and then scaling it to the range [0, 255].
  7. *
  8. * @param inputFilePath The path to the input binary file.
  9. * @param outputFilePath The path to the output normalized binary file.
  10. * @return True if normalization was successful, false otherwise.
  11. * @throws IOException If an I/O error occurs during file reading or writing.
  12. */
  13. public static boolean normalizeBinaryFile(String inputFilePath, String outputFilePath) throws IOException {
  14. try (InputStream inputStream = Files.newInputStream(Paths.get(inputFilePath));
  15. OutputStream outputStream = Files.newOutputStream(Paths.get(outputFilePath))) {
  16. byte[] fileBytes = inputStream.readAllBytes(); // Read all bytes from the input file
  17. if (fileBytes == null) {
  18. System.err.println("File is empty.");
  19. return false;
  20. }
  21. // Normalize the byte array to the range [0, 255]
  22. for (int i = 0; i < fileBytes.length; i++) {
  23. fileBytes[i] = Math.min(255, Math.max(0, fileBytes[i])); // Clamp values to [0, 255]
  24. }
  25. outputStream.write(fileBytes); // Write the normalized byte array to the output file
  26. return true;
  27. } catch (IOException e) {
  28. System.err.println("Error normalizing file: " + e.getMessage());
  29. return false;
  30. }
  31. }
  32. public static void main(String[] args) {
  33. if (args.length != 2) {
  34. System.out.println("Usage: java BinaryFileNormalizer <input_file_path> <output_file_path>");
  35. return;
  36. }
  37. String inputFilePath = args[0];
  38. String outputFilePath = args[1];
  39. try {
  40. boolean success = normalizeBinaryFile(inputFilePath, outputFilePath);
  41. if (success) {
  42. System.out.println("File normalization successful.");
  43. } else {
  44. System.out.println("File normalization failed.");
  45. }
  46. } catch (IOException e) {
  47. System.err.println("An error occurred: " + e.getMessage());
  48. }
  49. }
  50. }

Add your comment