java scanner txt_java scanner dos下输出到txt问题

展开全部

/*

你给出的代码是正确的,可以在控制台输出输入的信息。62616964757a686964616fe78988e69d8331333337393532

如果想要在文本文件中读写内容,就涉及到IO的知识了,不知道你是否有所了解。

下面是读写文件的完整代码,可以尝试理解一下。

看不懂也没关系,先保存下来,以后学了IO再拿出来,就会豁然开朗了。

*/

import java.io.*;

import java.util.Scanner;

public class Test9

{

static Scanner cin;

public static boolean FileOutDemo(String path)

{

boolean flag = false;

File file = new File(path);

FileWriter fos; // FileWriter 用于写入字符流

cin = new Scanner(System.in);

String name, sex, age, classname; // 声明姓名,性别,年龄,班级变量

System.out.println("请输入name:");

name = cin.next();

System.out.println("请输入sex:");

sex = cin.next();

System.out.println("请输入age:");

age = cin.next();

System.out.println("请输入classname:");

classname = cin.next();

try {

if (!file.exists()) { // 判断文件是否存在

file.createNewFile();

}

fos = new FileWriter(file, true); // 根据给定的文件名以及指示是否附加写入数据的 boolean

// 值来构造 FileWriter 对象。

BufferedWriter bw = new BufferedWriter(fos); // 创建一个使用默认大小输出缓冲区的缓冲字符输出流。

bw.write("姓名" + name + ",性别" + sex + ",年龄" + age + ",班级"+ classname);

bw.newLine(); // 写入一个行分隔符

//cin.close();

bw.close();

fos.close();

flag = true;

}

catch (IOException e)

{

e.printStackTrace();

}

return flag;

}

public static void FileInputDemo(String path)

{

File f = new File(path);

try {

byte bytes[] = new byte[512];

FileInputStream fis = new FileInputStream(f);

int rs = 0;

while ((rs = fis.read(bytes, 0, 512)) > 0) {

String s = new String(bytes, 0, rs);

System.out.println(s);

}

fis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String pathdemo = "e:\\text.txt";

System.out.println("请输入你想存入文本的内容");

FileOutDemo(pathdemo);

FileInputDemo(pathdemo);

if(cin!=null){

cin.close();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值