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; }
/** * Closes open files and resources associated with the open DDSImage. No other methods may be * called on this object once this is called. */ public void close() { try { if (chan != null) { chan.close(); chan = null; } if (fis != null) { fis.close(); fis = null; } buf = null; } catch (IOException e) { e.printStackTrace(); } }
public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("readandshow.txt"); FileChannel fc = fin.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); fc.read(buffer); buffer.flip(); int i = 0; while (buffer.remaining() > 0) { byte b = buffer.get(); System.out.println("Character " + i + ": " + ((char) b)); i++; } fin.close(); }
public static void main(String[] args) throws Exception { File blah = File.createTempFile("blah", null); blah.deleteOnExit(); ByteBuffer[] dstBuffers = new ByteBuffer[10]; for (int i = 0; i < 10; i++) { dstBuffers[i] = ByteBuffer.allocateDirect(10); dstBuffers[i].position(10); } FileInputStream fis = new FileInputStream(blah); FileChannel fc = fis.getChannel(); // No space left in buffers, this should return 0 long bytesRead = fc.read(dstBuffers); if (bytesRead != 0) throw new RuntimeException("Nonzero return from read"); fc.close(); fis.close(); }