Ejemplo n.º 1
0
 public static void main(String[] arguments) {
   try {
     // read byte data into a byte buffer
     String data = "friends.dat";
     FileInputStream inData = new FileInputStream(data);
     FileChannel inChannel = inData.getChannel();
     long inSize = inChannel.size();
     ByteBuffer source = ByteBuffer.allocate((int) inSize);
     inChannel.read(source, 0);
     source.position(0);
     System.out.println("Original byte data:");
     for (int i = 0; source.remaining() > 0; i++) {
       System.out.print(source.get() + " ");
     }
     // convert byte data into character data
     source.position(0);
     Charset ascii = Charset.forName("US-ASCII");
     CharsetDecoder toAscii = ascii.newDecoder();
     CharBuffer destination = toAscii.decode(source);
     destination.position(0);
     System.out.println("\n\nNew character data:");
     for (int i = 0; destination.remaining() > 0; i++) {
       System.out.print(destination.get());
     }
     System.out.println();
   } catch (FileNotFoundException fne) {
     System.out.println(fne.getMessage());
   } catch (IOException ioe) {
     System.out.println(ioe.getMessage());
   }
 }
Ejemplo n.º 2
0
 public static String readFile(String filename) {
   String s = "";
   FileInputStream in = null;
   // FileReader in = null;
   try {
     File file = new File(filename);
     byte[] buffer = new byte[(int) file.length()];
     // char[] buffer = new char[(int) file.length()];
     in = new FileInputStream(file);
     // in = new FileReader(file);
     in.read(buffer);
     s = new String(buffer);
     in.close();
   } catch (FileNotFoundException fnfx) {
     System.err.println("File not found: " + fnfx);
   } catch (IOException iox) {
     System.err.println("I/O problems: " + iox);
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ignore) {
         // ignore
       }
     }
   }
   return s;
 }