技术文档
欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进
使用datastream 读写文件之一
/* from http://java.sun.com/docs/books/tutorial/index.html */
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.eofexception;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
public class dataiodemo {
public static void main(string[] args) throws ioexception {
// write the data out
dataoutputstream out = new dataoutputstream(new fileoutputstream(
"invoice1.txt"));
double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
int[] units = { 12, 8, 13, 29, 50 };
string[] descs = { "java t-shirt", "java mug", "duke juggling dolls",
"java pin", "java key chain" };
for (int i = 0; i < prices.length; i++) {
out.writedouble(prices[i]);
out.writechar('/t');
out.writeint(units[i]);
out.writechar('/t');
out.writechars(descs[i]);
out.writechar('/n');
}
out.close();
// read it in again
datainputstream in = new datainputstream(new fileinputstream(
"invoice1.txt"));
double price;
int unit;
stringbuffer desc;
double total = 0.0;
try {
while (true) {
price = in.readdouble();
in.readchar(); // throws out the tab
unit = in.readint();
in.readchar(); // throws out the tab
char chr;
desc = new stringbuffer(20);
char linesep = system.getproperty("line.separator").charat(0);
while ((chr = in.readchar()) != linesep)
desc.append(chr);
system.out.println("you've ordered " + unit + " units of "
+ desc + " at $" + price);
total = total + unit * price;
}
} catch (eofexception e) {
}
system.out.println("for a total of: $" + total);
in.close();
}
}
扫描关注微信公众号