java结果输出到文件_Java如何将控制台上的结果保存到文件

无论是二进制数据还是字符数据(文本数据),都可以用文件输出流java.io.FileOutputStream,以字节流的方式保存到指定文件。

package test;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

class LogWrite{

private static boolean fileLog = true;

private static String logFileName = "E:/workspace/Java/result/result.txt";//指定程序执行结果保存的文件路径

public static OutputStream getOutputStream() throws IOException{

if(fileLog)

{

File file = new File(logFileName);

if(!file.exists())

file.createNewFile();

return new FileOutputStream(file, true);

}

else

{

return System.out;

}

}

public static void log(String info) throws IOException{

OutputStream out = getOutputStream();

out.write(info.getBytes("utf-8"));

}

}

public class Test1 {

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

// TODO Auto-generated method stub

LogWrite.log("hello world");//"hello world"会保存到result.txt文件中

}

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,请看下面的代码示例: ```java import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Student { private String studentId; private String name; public Student(String studentId, String name) { this.studentId = studentId; this.name = name; } public String getStudentId() { return studentId; } public String getName() { return name; } } public class Main { public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); // 从键盘输入学生信息 Scanner scanner = new Scanner(System.in); System.out.print("请输入学生数量:"); int numStudents = scanner.nextInt(); for (int i = 0; i < numStudents; i++) { System.out.println("请输入第 " + (i + 1) + " 个学生的学号和姓名:"); String studentId = scanner.next(); String name = scanner.next(); Student student = new Student(studentId, name); studentList.add(student); } // 将学生信息保存文件中 try { FileWriter writer = new FileWriter("students.txt"); for (Student student : studentList) { writer.write(student.getStudentId() + " " + student.getName() + "\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } // 从文件中查询所有学生信息并输出控制台 try { BufferedReader reader = new BufferedReader(new FileReader("students.txt")); String line; while ((line = reader.readLine()) != null) { String[] info = line.split(" "); String studentId = info[0]; String name = info[1]; System.out.println("学号:" + studentId + ",姓名:" + name); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 请注意,这段代码会在当前目录创建一个名为 "students.txt" 的文件,用于保存学生信息。如果该文件已存在,则会覆盖原有内容。同时,从键盘输入的学生信息和从文件中查询的学生信息会输出控制台上。 你可以根据自己的需求,对代码进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值