Created
July 30, 2016 07:35
-
-
Save tomoTaka01/65c0151e9772a367b7dd2bf2f454bba6 to your computer and use it in GitHub Desktop.
Java NIO -> NIO2 (UnmappableCharacterException error occur)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sample; | |
import java.io.BufferedWriter; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStreamWriter; | |
import java.nio.charset.Charset; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
public class Sample { | |
public static void main(String... args) throws IOException { | |
Sample sample = new Sample(); | |
sample.writeNIO(); | |
sample.writeNIO2(); | |
} | |
void writeNIO() { | |
String val = "Pockémon"; | |
try (BufferedWriter writer = new BufferedWriter( | |
new OutputStreamWriter(new FileOutputStream("/Users/tomo/NIO.txt"), Charset.forName("sjis")))) { | |
writer.write(val); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
void writeNIO2() throws IOException { | |
String val = "Pockémon"; | |
Path path = Paths.get("/Users", "tomo", "NIO2.txt"); | |
try (BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("sjis"));) { | |
writer.write(val); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sample; | |
import static org.junit.Assert.assertTrue; | |
import java.io.IOException; | |
import java.nio.charset.UnmappableCharacterException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import org.junit.Before; | |
import org.junit.Test; | |
public class SampleTest { | |
Sample sample; | |
@Before | |
public void setUp() throws Exception { | |
sample = new Sample(); | |
} | |
@Test | |
public void testWriteNIO() { | |
sample.writeNIO(); | |
Path path = Paths.get("/Users", "tomo", "NIO.txt"); | |
boolean exists = Files.exists(path); | |
assertTrue(exists); | |
} | |
@Test(expected = UnmappableCharacterException.class) | |
public void testWriteNIO2() throws IOException { | |
sample.writeNIO2(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The file NIO.txt is Pock?mon.
When you refactor from NIO to NIO2 , you will have UnmappableCharacterException.