Ask Your Question
4

How can the BOM character be skipped in java utils.Properties?

asked 2022-07-07 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-03-18 09:00:00 +0000

nofretete gravatar image

To skip the BOM (Byte Order Mark) character in java utils.Properties, you can use the following code:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class Main {
  public static void main(String[] args) throws IOException {
    Properties props = new Properties();

    // Open the input stream with UTF-8 encoding to read the file
    FileInputStream input = new FileInputStream("file.properties");
    InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
    BufferedReader bufferedReader = new BufferedReader(reader);

    // Skip the BOM character if present
    bufferedReader.mark(1);
    if (bufferedReader.read() != 0xfeff) {
        bufferedReader.reset();
    }

    // Load the properties file
    props.load(bufferedReader);

    // Close the streams
    bufferedReader.close();
    reader.close();
    input.close();

    // Print the properties
    System.out.println(props);
  }
}

In this code, we first open the input stream with UTF-8 encoding to read the file. We then create a BufferedReader to skip the BOM character if present. We use the mark() method to mark the current position in the stream and then read the first byte to check if it is the BOM. If it is not the BOM, we reset the stream to the marked position. Finally, we load the properties file using the load() method of the Properties class and print the properties.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-07 11:00:00 +0000

Seen: 10 times

Last updated: Mar 18 '23