Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Oct 2010
    Posts
    29
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Java ASCII file output

    When I try to output an ASCII value to a file, it sometimes writes the wrong value. Example:

    Code:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.PrintWriter;
    
    public class test {
    	public static void main(String args[]){
    		                          //Supposed to:
    		writeFile("./test.txt"); //write ASCII 147
    		readFile("./test.txt"); //read ASCII 147
    	}
    	
    	public static boolean writeFile(String path){
    		try{
    			PrintWriter fo = new PrintWriter(new FileOutputStream(new File(path)));
    			fo.print((char) 147); //WRITES "?" TO FILE (ASCII 63, NOT 147)
    			fo.close();
    		}catch(Exception e){
    			return true;
    		}
    		return false;
    	}
    	
    	public static boolean readFile(String path){
    		try {
    			BufferedReader fi = new BufferedReader(new FileReader(path));
    			char c[] = fi.readLine().toCharArray();
    			System.out.println((int) c[0]); //OBVIOUSLY PRINTS 63 INSTEAD OF 147
    			fi.close();
    			return true;
    		} catch (Exception e){
    			e.printStackTrace();
    			return false;
    		}
    	}
    }
    What am I doing wrong? Any help would be great.
    PHP - MySQL - JavaScript - AJAX - HTML/XHTML/XML - CSS - Java - C++

  • #2
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,725
    Thanks
    41
    Thanked 191 Times in 190 Posts
    After 128 you enter extended ASCII which it is not handling and is serving up a "?" if you put in watch window it actually will return blank- you need to convert extended ASCII to a byte[] and then display it accordingly
    Code:
    public class demo {
    	public static void main(String[] args) throws IOException {
    		System.out.println("demo");
    		int b = 147;
    		char _b = (char)b;
    		String B = Character.toString(_b);
    		byte[] bb = B.getBytes("UTF-32");
    		System.out.println(new String(bb, "MacGreek"));	
    	}
    here are some ref langs: link

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •