diff --git a/xchart/src/main/java/org/knowm/xchart/BitmapEncoder.java b/xchart/src/main/java/org/knowm/xchart/BitmapEncoder.java index f100ac27..0e958b45 100644 --- a/xchart/src/main/java/org/knowm/xchart/BitmapEncoder.java +++ b/xchart/src/main/java/org/knowm/xchart/BitmapEncoder.java @@ -39,13 +39,16 @@ private BitmapEncoder() {} */ public static String addFileExtension(String fileName, BitmapFormat bitmapFormat) { - String fileNameWithFileExtension = fileName; final String newFileExtension = "." + bitmapFormat.toString().toLowerCase(); - if (fileName.length() <= newFileExtension.length() + final String fileNameWithFileExtension; + if (fileName.length() < newFileExtension.length() || !fileName - .substring(fileName.length() - newFileExtension.length(), fileName.length()) + .substring(fileName.length() - newFileExtension.length()) .equalsIgnoreCase(newFileExtension)) { fileNameWithFileExtension = fileName + newFileExtension; + } else { + // This is to ensure the lower-case for the extension + fileNameWithFileExtension = fileName.substring(0, fileName.length() - newFileExtension.length()) + newFileExtension; } return fileNameWithFileExtension; } diff --git a/xchart/src/test/java/org/knowm/xchart/BitmapEncoderTest.java b/xchart/src/test/java/org/knowm/xchart/BitmapEncoderTest.java new file mode 100644 index 00000000..68d74f21 --- /dev/null +++ b/xchart/src/test/java/org/knowm/xchart/BitmapEncoderTest.java @@ -0,0 +1,26 @@ +package org.knowm.xchart; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +public class BitmapEncoderTest { + + @Test + public void testAddFileExtension() { + String fileName1 = "image"; + String fileName2 = "image.png"; + String fileName3 = "image.PNG"; + + for (String s : Arrays.asList(fileName1, fileName2, fileName3)) { + assertEquals("image.png", BitmapEncoder.addFileExtension(s, BitmapEncoder.BitmapFormat.PNG)); + } + assertEquals("z.bmp", BitmapEncoder.addFileExtension("z", BitmapEncoder.BitmapFormat.BMP)); + assertEquals("asdf.bmp", BitmapEncoder.addFileExtension("asdf", BitmapEncoder.BitmapFormat.BMP)); + assertEquals(".bmp", BitmapEncoder.addFileExtension(".bmp", BitmapEncoder.BitmapFormat.BMP)); + assertEquals(".bmp", BitmapEncoder.addFileExtension(".BmP", BitmapEncoder.BitmapFormat.BMP)); + } +}