Switch to full style
General Java code examples
Post a reply

Write and Read to File In Java Example

Wed Feb 06, 2013 8:49 pm

Write and Read to File In Java Code implementation Example
java code
import java.io.*;

public class DataIOTest {
public static void main(String[] args) throws IOException {

//File to start in
DataOutputStream out = new DataOutputStream(new
FileOutputStream("main.txt"));

double[] prices = { 12.45, 3.54, 23.53, 6.75, 2.53 };
int[] units = { 12, 8, 13, 29, 50 };
String[] descs = { " T-shirt1",
"T-shirt2",
"T-shirt3",
"T-shirt4",
"T-shirt5" };

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("main.txt"));

double price;
int unit;
String desc;
double total = 0.0;

try {
while (true) {
price = in.readDouble();
in.readChar(); // skip the tab
unit = in.readInt();
in.readChar(); // skip the tab
desc = in.readLine();
System.out.println("Order " +
unit + " units of " +
desc + " at $" + price);
total = total + unit * price;
}
} catch (EOFException e) {
}
System.out.println("Total: $" + total);
in.close();
}
}




Post a reply
  Related Posts  to : Write and Read to File In Java Example
 File write read     -  
 Read and Write to file using ASP     -  
 Read and write CSV file     -  
 How to read and write to CSV file from python     -  
 Read double values type from file in java     -  
 Write to file using php     -  
 Write Vector list to File     -  
 Read csv file     -  
 read from file in C++     -  
 File read by char     -  

Topic Tags

Java Files and I/O