import java.io.*;
import java.nio.file.*;
public class BinaryFileNormalizer {
/**
* Normalizes the data of a binary file by converting it to a byte array
* and then scaling it to the range [0, 255].
*
* @param inputFilePath The path to the input binary file.
* @param outputFilePath The path to the output normalized binary file.
* @return True if normalization was successful, false otherwise.
* @throws IOException If an I/O error occurs during file reading or writing.
*/
public static boolean normalizeBinaryFile(String inputFilePath, String outputFilePath) throws IOException {
try (InputStream inputStream = Files.newInputStream(Paths.get(inputFilePath));
OutputStream outputStream = Files.newOutputStream(Paths.get(outputFilePath))) {
byte[] fileBytes = inputStream.readAllBytes(); // Read all bytes from the input file
if (fileBytes == null) {
System.err.println("File is empty.");
return false;
}
// Normalize the byte array to the range [0, 255]
for (int i = 0; i < fileBytes.length; i++) {
fileBytes[i] = Math.min(255, Math.max(0, fileBytes[i])); // Clamp values to [0, 255]
}
outputStream.write(fileBytes); // Write the normalized byte array to the output file
return true;
} catch (IOException e) {
System.err.println("Error normalizing file: " + e.getMessage());
return false;
}
}
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java BinaryFileNormalizer <input_file_path> <output_file_path>");
return;
}
String inputFilePath = args[0];
String outputFilePath = args[1];
try {
boolean success = normalizeBinaryFile(inputFilePath, outputFilePath);
if (success) {
System.out.println("File normalization successful.");
} else {
System.out.println("File normalization failed.");
}
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
Add your comment