本文目录一览:
- 1、用java编写程序,使用文件输出流,向文件分别写入如下类型的数据:int、double和字符串
- 2、java中怎样把double类型和当前时间用IO流写入到文件txt中?、
- 3、java写double入txt 3 6 7 为什么不一样了
用java编写程序,使用文件输出流,向文件分别写入如下类型的数据:int、double和字符串
import java.io.*;
class Test
{
public static void main(String args[])throws IOException
{
writeData();
}
public static void writeData()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"));
String line = null;
while((line = br.readLine())!=null)
{
if(line.equals("exit")) //录入的字符串是"exit",则退出
break;
try
{
dos.writeInt(Integer.parseInt(line)); //如果录入的是int型,则向文件“data.txt”中写入int型的数据
}
catch (NumberFormatException e1)
{
try
{
dos.writeDouble(Double.parseDouble(line)); //录入的是double型,“data.txt”中写入double型的数据
}
catch (NumberFormatException e2)
{
bw.write(line); //不是int,double,即使String类型,就将String类型写入
}
}
}
br.close();
dos.close();
bw.close();
}
}
java中怎样把double类型和当前时间用IO流写入到文件txt中?、
package com.winjing.testing.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
PrintWriter pw;
try {
Double num = 1.2;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(new Date());
pw = new PrintWriter(new FileWriter( "D:\\test.txt" ));
pw.print(num + "\t" + time);
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void DOWriteTxt(String file, String txt) {
try {
FileOutputStream os = new FileOutputStream(new File(file), true);
os.write((txt + "\n").getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}
java写double入txt 3 6 7 为什么不一样了
对于double类型的 做 一下精度处理
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test {
public static void main(String[] args) throws IOException {
RandomAccessFile rf = new RandomAccessFile("D://java.txt", "rw");
String s = "";
for (int i = 0; i 10; i++) {
s = String.valueOf(i);
s = s + "\r\n ";
rf.writeBytes(s);
}
for (int i = 0; i 10; i++) {
s = String.format("%.1f", (i * 1.1));
s = s + "\r\n ";
rf.writeBytes(s);
}
// rf.close();
rf = new RandomAccessFile("D://java.txt", "rw");
for (int i = 0; i 20; i++) {
s = rf.readLine();
System.out.println("Value " + i + ": " + s);
}
rf.close();
}
}