文件fos1.txt中的结果输出是d但是我希望它在文件中是100,我该怎么办?
public class Byteo {
public static void main(String[] args) {
try {
FileOutputStream fos1 = new FileOutputStream("G:\\fos1.txt");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int x = 100;
bos.write(x);
try {
bos.writeTo(fos1);
bos.flush();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
write(int b)
将int x = 100
解释为字节码,因此,将编码的字节写入文件。
写(int b) 将指定的字节写入此字节数组输出 流。
你可以这样做:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int x = 100;
bos.write(String.valueOf(x).getBytes(StandardCharsets.UTF_8));
答案 1 :(得分:1)
您不需要在此处使用ByteArrayOutputStream。更好的方法是使用编写器来处理大部分转换,并显式声明从CharSequence转换为字节时要使用的编码:
public static void main(String[] args) {
String path = "...";
int x = 100;
try (Writer writer = new OutputStreamWriter(new FileOutputStream(path),
StandardCharsets.UTF_8)) {
writer.write(Integer.toString(x));
} catch (IOException e) {
throw new RuntimeException("Something erred", e);
}
}
答案 2 :(得分:0)
public class Byteo {
public static void main(String[] args) throws IOException {
int x = 100;
FileWriter fw = new FileWriter("fos1.txt");
try {
fw.write(String.valueOf(x));
} finally {
fw.flush();
fw.close();
}
}
}
答案 3 :(得分:0)
您必须将int / Integer / char转换为String,以免被解释为字节代码。
所以你以gc.save();
gc.translate(center.x, center.y);
gc.rotate(this.angle);
gc.strokeRect(0,0, this.width, this.height);
gc.restore();