先写一个自定义类
public class Test {
private String string;
private int anInt;
private double aDouble;
public Test(String string, int anInt, double aDouble) {
this.string = string;
this.anInt = anInt;
this.aDouble = aDouble;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getAnInt() {
return anInt;
}
public void setAnInt(int anInt) {
this.anInt = anInt;
}
public double getaDouble() {
return aDouble;
}
public void setaDouble(double aDouble) {
this.aDouble = aDouble;
}
@Override
public String toString() {
return "我是"+this.string
+",今年"+this.anInt+"岁"
+",身高"+this.aDouble+"米.\n";
}
}
方法有两种,原理我用注释的方式写在代码里
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class Testmain {
public static void main(String[] args){
List<Test> tests=new ArrayList<>();
tests.add(new Test("李华",18,1.8));
tests.add(new Test("小明",19,1.83));
tests.add(new Test("小红",20,1.55));
// System.out.println(tests);
fileout(tests);
//这个办法方便但是修改输出管道后不知道怎么改回去,控制台输出用不了了
filecopy(tests);
}
private static void fileout(List<Test> tests) {
PrintStream printStream=null;
File file=null;
try {
file= new File("C:\\Users\\XW\\IdeaProjects\\java\\src\\test\\iotest\\iotest_1\\test.txt");
printStream=new PrintStream(file);
file.createNewFile();//清空文件
System.setOut(printStream);//改变输出管道
System.out.println(tests);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if (printStream != null) {
printStream.close();
}
}
System.out.println(tests);
}
private static void filecopy(List<Test> tests) {
FileOutputStream fileOutputStream=null;
String pathname="C:\\Users\\XW\\IdeaProjects\\java\\src\\test\\iotest\\iotest_1\\test.txt";
byte[] bytes=null;
try {
fileOutputStream=new FileOutputStream(pathname);
// bytes= tests.get(0).toString().getBytes(StandardCharsets.UTF_8);
// fileOutputStream.write(bytes);
// fileOutputStream.flush();
// bytes=tests.get(1).toString().getBytes(StandardCharsets.UTF_8);
// fileOutputStream.write(bytes);
// fileOutputStream.flush();
//测试
for (Test t: tests) {
bytes=t.toString().getBytes(StandardCharsets.UTF_8);//把字符串打成byte数组
fileOutputStream.write(bytes);
fileOutputStream.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
System.out.println("关闭管道失败!");
}
}
//version1.5改动
//用于商品信息修改后实时覆写文件
}
}
第一种只能在程序即将结束的末尾用,因为我不会把管道改回来,第二种就稳稳的,没有问题。运行出来就是这样的。
没有毛病。
5月的最后一天了,下个月见,瑞思拜!