I'm developing a project for my university. I'm having trouble while trying to convert a byte array to a string.
So, first I'm saving the contents of a java file in a long blob type column in MySql like this:
Path path = Paths.get(file.getAbsolutePath());
Charset charset = StandardCharsets.UTF_8;
String fileContent = new String(Files.readAllBytes(path), charset);
...
String query = "INSERT INTO MY_TABLE(FILE_CONTENT) VALUES (?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, fileContent);
preparedStmt.executeUpdate();
The file contains some words with Spanish accents, which are inserted in the database correctly (as shown in the image): data saved in MySql
Later, in my application I need to read the information from this column. I did like this:
String query = "SELECT * FROM MY_TABLE";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
Blob file= rs.getBlob("FILE_CONTENT");
String fileContent= new String(file.getBytes(1l, (int) file.length()), StandardCharsets.UTF_8);
When I print fileContent the character é is not recognized. I get a text with something like this:
driver.findElement(By.id("FNAME")).sendKeys("Leonardo Pa�z")
I have tried what is suggested in these posts (encoding decoding of byte array to string without data loss), (Encode String to UTF-8), (Java Strings Character Encoding - For French - Dutch Locales) and some blogs like this one, but I haven't been able to find a solution to this problem.
Any help will be really appreciated :)