创建一个程序,从控制台读取文本,并将其写入到文件中。用户输入一个空行,表示结束输入。
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
File file;
FileWriter fw = null;
file = new File("/usr/Test.txt");
try {
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
Scanner in = new Scanner(System.in);
while (true) {
String s = in.nextLine();
if (s.equals(""))
break;
fw.write(s);
fw.flush();
}
System.out.println("写入数据成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
一个这样的程序:让用户输入其全名,年龄和电话号码,以特定的格式显示这些消息,并显示用户的姓名的首字母。
import java.util.Scanner;
class File0 {
private String name;
private int age;
private String tel;
private char sig;
File0(String name, int age, String tel) {
name(name);
age(age);
tel(tel);
getFirstChar(name);
}
void name(String name) {
this.name = name;
}
void age(int age) {
this.age = age;
}
void tel(String tel) {
this.tel = tel;
}
void print() {
System.out.print(this.sig + "\t姓名" + this.name);
System.out.print("\t年龄" + this.age);
System.out.print("\t电话" + this.tel);
}
private void getFirstChar(String str) {//方法一
this.sig = str.charAt(0);// 索引下标为0的字符
}
}
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("输入姓名: ");
String n = scan.nextLine();
System.out.print("输入年龄: ");
int a = scan.nextInt();
Scanner scan0 = new Scanner(System.in);
System.out.print("输入电话: ");
String t = scan0.nextLine();
File0 f = new File0(n, a, t);
f.print();
}
}