4 import lejos.nxt.Flash;
\r
7 public class FileOutputStream extends OutputStream {
\r
10 * Current page this stream is writing to
\r
12 private int page_pointer;
\r
15 * Current byte in *buffer* (buff below) it is writing to
\r
17 private int data_pointer;
\r
20 * A buffer of the same size as a page of flash memory.
\r
22 private byte [] buff;
\r
24 private boolean append = false;
\r
26 * File attached to this stream
\r
31 * create a new OutputStream to write to this file, starting at the beginning of the file.
\r
32 * @param f the file this stream writes to
\r
34 public FileOutputStream(File f)
\r
39 * create a new OutputStream to write to this file
\r
40 * @param f the file this stream writes to
\r
41 * @param append if true this sream will start writing at the end of the file, otherwise at the beginning
\r
43 public FileOutputStream(File f, boolean append) {
\r
44 this.append = append;
\r
46 buff = new byte[File.BYTES_PER_PAGE];
\r
47 page_pointer = file.page_location;
\r
48 data_pointer = 0; // Start of first page
\r
52 page_pointer = file.page_location + file.file_length/File.BYTES_PER_PAGE ;
\r
53 data_pointer = file.file_length%File.BYTES_PER_PAGE;
\r
54 Flash.readPage(buff, page_pointer);
\r
56 else file.file_length = 0;// can this cause trouble?
\r
60 * write 1 byte to the file; if necessary, file will be moved become the last file in memory
\r
62 public void write(int b) throws IOException {
\r
63 if(file.page_location < 0) throw new IOException(); // "File has not been created!"
\r
64 buff[data_pointer] = (byte)b;
\r
66 file.file_length++;
\r
67 if(data_pointer >= File.BYTES_PER_PAGE)
\r
69 if(file.getIndex()< ( File.totalFiles -1))
\r
72 page_pointer = file.page_location + file.file_length/File.BYTES_PER_PAGE;
\r
74 flush(); // Write to flash
\r
75 page_pointer++; // Move to next page
\r
80 public void flush() throws IOException {
\r
81 Flash.writePage(buff, page_pointer);
\r
84 * write the buffer to flash memory and update the file parameters in flash
\r
85 * Resets pointers, so file can be writen again from beginning with the same output stream.
\r
87 public void close() throws IOException {
\r
88 // !! Alternate implementation: If this is a new file, perhaps only
\r
89 // write the file table information AFTER close() called so
\r
90 // incomplete/partial files don't exist.
\r
92 File.writeTable(File.listFiles()); // Updates file size for this file.
\r
93 page_pointer = file.page_location;
\r
94 data_pointer = 0; // Start of first page
\r