java操作dat文件
1、打开myeclipse file --》new--》web project
具体操作如下图所示:
1、第一步:首先编写文件操作类FileUtil。
1、编写写入文件内容的操作rewrite
2、编写读取文件内容的操作readString
3、具体实现代码如下所示:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileUtil {
public static void rewrite(File file, String data) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String readString(File file) {
BufferedReader br = null;
String data = "";
try {
br = new BufferedReader(new FileReader(file));
for (String str = null; (str = br.readLine()) != null;) {
data += (str+"\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data;
}
}
2、第二步:测试生成写入dat内容。
1、dat文件的操作和一般的txt文件操作基本一样
2、file默认生成文件位置在当前项目下
代码如下:
import java.io.File;
public class TestDat {
public static void main(String[] args) {
File file = new File("test.dat");
FileUtil.rewrite(file, "第一行测试数据");
}
}
3、第三步:测试读取dat中的内容。
1、编辑生成的文件中的内容
2、将内容输出到控制台展示
3、具体代码如下所示:
import java.io.File;
public class TestDat {
public static void main(String[] args) {
File file = new File("test.dat");
if (file.exists()) {
String str = FileUtil.readString(file);
System.out.println(str);
} else {
System.out.println("文件不存在!");
}
}
}