无法将上面的一些 ascii 值写入 java 中的文件
我正在编写一个 java 代码来将 ASCII 字符写入文件。但是,当我尝试将 ASCII 值大于 140 或小于 32 的任何字符写入文本文件时,我得到一个空白文件。它不会向文件写入任何内容。我的程序对于 32 到 140 之间的所有值都能成功运行。请帮忙...... 这是代码
public class IO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileOutputStream fs=new FileOutputStream("C:/Users/Shantanu/Desktop/abc.txt");
fs.write(143);
fs.close();
System.out.println("finished");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am writing a java code to write ASCII characters to a file. But when I try to write any character of ASCII value of more than 140 or less than 32 to a text file, I get a blank file. It does not write anything to the file. My program is working successfully for all values between 32 and 140. Please help.....
this is the code
public class IO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileOutputStream fs=new FileOutputStream("C:/Users/Shantanu/Desktop/abc.txt");
fs.write(143);
fs.close();
System.out.println("finished");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为你超出了 ASCII 值范围。请改用 StringWriter 并将所需值作为字符串传递。
Because you are outside ASCII value range. Use StringWriter instead and pass desired values as string.
当我运行这个程序时,
我得到
既然你写了 1 个字节,你应该期望它是 1 个字节长。
但是,如果您尝试将其读取为 UTF-8 或某种其他编码,则这可能少于 1 个字符(例如,在 UTF-8 中,您需要 2-3 个字节来存储大约 127 个字符)
When I run this
I get
Since you write 1 byte, you should expect it to be 1 byte long.
However if you attempt to read this as a UTF-8 or some other encoding, this may be less than 1 character (e.g. in UTF-8 you need 2-3 bytes for characters about 127)
来自维基百科:
ASCII 包括 128 个字符的定义:33 个是非打印控制字符(现在大部分已过时),它们影响文本和空间的处理方式; 94是可打印的字符,空格被认为是不可见的图形。
ASCII 保留前 32 个代码(十进制数字 0-31)作为控制字符。
代码127正式命名为“删除”。
但存在扩展 ASCII。
因此,要写入扩展 ASCII,您需要使用如下编码:
在这种情况下,您会收到类似: ®。因此输出超过 127 的 ASCII(8 位非 7 位,如 ASCII USA)需要使用编码。希望这有帮助。
Fromw Wikipedia:
ASCII includes definitions for 128 characters: 33 are non-printing control characters (now mostly obsolete) that affect how text and space is processed; 94 are printable characters, and the space is considered an invisible graphic.
ASCII reserves the first 32 codes (numbers 0–31 decimal) for control characters.
Code 127 is officially named "delete".
But exists Extended ASCII.
So for write extended ASCII you need use encoding like:
In this case you receive like: ®. So output of ASCII more than 127 (8 bit non 7 bit as ASCII USA) need use encoding. Hope this helps.