0%

Java 文件基本技术(三):文本文件和字符流

1. 将字符串 “hello, 123,老隋” 写到文件 hello.txt 中,编码格式为 GB-2312

1
2
3
4
5
6
7
Writer writer = new OutputStreamWriter(new FileOutputStream("hello.txt"), "GB2312);
try {
String str = "hello, 123, 老隋";
writer.write(str);
} finally {
writer.close();
}

2. 接上题,将上面写入的文件读进来

1
2
3
4
5
6
7
8
9
//假定一次 read() 调用就读到了所有内容,且假定长度不超过 1024。为了确保读到所有内容,可以借助 CharArrayWriter 或 StringWriter
Reader reader = new InputStreamReader(new FileInputStream("hello.txt"), "GB2312");
try {
char[] cbuf = new char[1024];
int charsRead = reader.read(cbuf);
System.out.println(new String(cbuf, 0, charsRead));
} finally {
reader.close();
}

3. 使用 CharArrayWriter,改进上面的读写代码,确保将所有文件内容读入

1
2
3
4
5
6
7
8
9
10
11
12
Reader reader = new InputStreamReader(new FileInputStream("hello.txt"), "GB2312");
try {
CharArrayWriter writer = new CharArrayWriter();
char[] cbuf = new char[1024];
int charsRead = 0;
while((charsRead=reader.read(cbuf)) != -1) {
writer.write(cbuf, 0, charsRead);
}
System.out.println(writer.toString());
} finally {
reader.close();
}

4. 使用可读的文本进行保存,一行保存一条学生信息,学生字段之间用逗号分隔

  • 使用缓冲类,按行读写

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public static void writeStudents(List<Student> students) throws IOException {
    BufferedWriter writer = null;
    try {
    writer = new BufferedWriter(new FileWriter("students.txt));
    for(Student s : students) {
    writer.write(s.getName() + ", " + s.getAge() + ", " + s.getScore());
    writer.newLine();
    }
    } finally {
    if(writer != null) {
    writer.close();
    }
    }
    }
  • 保存后的文件内容显示为

    1
    2
    张三,1880.9
    李四,1767.5
  • 从文件中读取

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    public static List<Student> readStudents() throws IOException {
    BufferedReader reader = null;
    try {
    reader = new BufferedReader(new FileReader("students.txt"));
    List<Student> students = new ArrayList<> ();
    //字符 \r 或 \n 或 \r\n 被视为换行符,readLine() 返回一行内容,但不会包含换行符
    String line = reader.readLine();
    while(line != null) {
    String[] fields = line.split(", ");
    Student s = new Student();
    s.setName(fields[0]);
    s.setAge(Integer.parseInt(fields[1]));
    s.setScore(Double.parseDouble(fields[2]));
    students.add(s);
    line = reader.readLine();
    }
    return students;
    } finally {
    if(reader != null) {
    reader.close();
    }
    }
    }
  • 使用 PrintWriter 保存学生列表

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public static void writeStudents(List<Student> students) throws IOException {
    PrintWriter writer = new PrintWriter("students.txt);
    try {
    for(Student s : students) {
    writer.println(s.getName() + ", " + s.getAge() + ", " + s.getScore());
    }
    } finally {
    if(writer != null) {
    writer.close();
    }
    }
    }
  • 使用 Scanner 解析学生记录

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public static List<Student> readStudents() throws IOException {
    BufferedReader reader = new BufferedReader(new Filereader("students.txt"));
    try {
    List<Student> students = new ArrayList<Student> ();
    String line = reader.readLine();
    while(line != null) {
    Student s = new Student();
    Scanner scanner = new Scanner(line).useDelimiter(", ");
    s.setName(scanner.next());
    s.setAge(scanner.nextInt());
    s.setScore(scanner.nextDouble());
    students.add(s);
    line = reader.readLine();
    }
    return students;
    } finallly {
    reader.close();
    }
    }

5. 从键盘接受一个整数并输出

1
2
3
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(num);

6. 复制 Reader 到 Writer

1
2
3
4
5
6
7
public static void copy(final Reader input, final Writer output) throws IOException {
char[] buf = new char[4096];
int charsRead = 0;
while((charsRead = input.read(buf)) != -1) {
output.write(buf, 0, charsRead);
}
}

7. 将文件全部内容读入到一个字符串,参数为文件名和编码类型

1
2
3
4
5
6
7
8
9
10
11
12
13
public static String readFileToString(final String fileName, final String encoding) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), encoding));
StringWriter writer = new StringWriter();
copy(reader, writer);
return writer.toString();
} finally {
if(reader != null) {
reader.close();
}
}
}

8. 将字符串写到文件,参数为文件名、字符串内容和编码类型

1
2
3
4
5
6
7
8
9
10
11
public static void writeStringToFile(final String fileName, final String data, final String encoding) throws IOException {
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
writer.write(data);
} finally {
if(writer != null) {
writer.close();
}
}
}

9. 按行将多行数据写到文件,参数为文件名、编码类型、行的集合

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void writeLines(final String fileName, final String encoding, final Collection<?> lines) throws IOException {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, encoding);
for(Object line : lines) {
writer.println(line);
}
} finally {
if(writer != null) {
writer.close();
}
}
}

10. 按行将文件内容读到一个列表中,参数为文件名、编码类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static List<String> readLines(final String fileName, final String encoding) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), encoding));
List<String> list = new ArrayList<> ();
String line = reader.readLine();
while(line != null) {
list.add(line);
line = reader.readLine();
}
return list;
} finally {
if(reader != null) {
reader.close();
}
}
}
-------------------- 本文结束感谢您的阅读 --------------------