开发者

Unable to write some ascii values above to a file in java

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 prog开发者_C百科ram 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();
    }

}

}


Because you are outside ASCII value range. Use StringWriter instead and pass desired values as string.


When I run this

final String name = "abc.txt";

FileOutputStream fs = new FileOutputStream(name);
fs.write(143);
fs.close();

System.out.println("finished, file.length=" + new File(name).length());

I get

finished, file.length=1

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)


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:

System.setProperty("file.encoding", "Cp1252");
FileOutputStream fs = new FileOutputStream("C:/abc.txt");
char c=(char)174;
fs.write(c);
fs.close();

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜