我有程序读取用户输入然后写入文件。 在该程序读取该文件并制作一些基本的算术函数之后。 然后结果显示在屏幕上供用户使用。之后我要清除该文件,因为它就像程序缓存一样,不需要永久存储。
一切都很好,我可以清除文件,但我有一个奇怪的例外:
java.io.UnsupportedEncodingException
并且程序停止。
我的代码: 该文件看起来像这样
2013 Jūnijs 1500.0 80 125 293.7 151.25 1055.05
2013 Jūlijs 1150.0 80 125 218.94 112.75 818.31
2013 Septembris 1550.0 80 125 304.38 156.75 1088.87
使用以下代码清除文件:
public static void Clear_file() throws IOException{
System.out.println("Notīram failu");
clear = new Formatter(new FileWriter(user_name()+".txt", true));
FileOutputStream erasor = new FileOutputStream(user_name()+".txt");
erasor.write((new String().getBytes("")));
erasor.close();
}
我阅读了指南并且写得像这样: 如果给定的字符集不在该列表中,那么可以肯定会抛出此错误。
我很困惑,因为在文件中只是String和double类型的数据。
如何避免这种异常?
谢谢:)
答案 0 :(得分:2)
new String().getBytes("")
您没有提供charset的名称,这就是抛出异常的原因。
尝试设置一个,你会发现它运行正常。
System.out.println(Arrays.toString(new String("test").getBytes("UTF-8")));
输出:
[116,101,115,116]
答案 1 :(得分:1)
erasor.write((new String().getBytes("")));
在这里,您要求空String对象获取一个名为""
的编码中编码的字节数组。 (无名)。当然,没有名为""
的字符编码。
要清除文件,请使用以下内容:
new FileOuputStream(file).close();