Skip to content

Instantly share code, notes, and snippets.

@tomoTaka01
Created July 30, 2016 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomoTaka01/65c0151e9772a367b7dd2bf2f454bba6 to your computer and use it in GitHub Desktop.
Save tomoTaka01/65c0151e9772a367b7dd2bf2f454bba6 to your computer and use it in GitHub Desktop.
Java NIO -> NIO2 (UnmappableCharacterException error occur)
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);
}
}
}
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();
}
}
@tomoTaka01
Copy link
Author

The file NIO.txt is Pock?mon.
When you refactor from NIO to NIO2 , you will have UnmappableCharacterException.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment