8-1 写入日志文件 (0 分)
 

编写程序,要求:用户在键盘每输入一行文本,程序将这段文本显示在控制台中。当用户输入的一行文本是“exit”(不区分大小写)时,程序将用户所有输入的文本都写入到文件log.txt中,并退出。(要求:控制台输入通过流封装System.in获取,不要使用Scanner)

import java.io.*;

public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new FileWriter(new File("log.txt")));
String s;
while(!(s = br.readLine()).equalsIgnoreCase("exit"))
{
System.out.print(s);
bw.write(s);
bw.newLine();
}
}catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
8-2 文件和目录输出 (20 分)
 

查看File类的API文档,使用该类实现一个类FileList,它提供两个静态方法:1)readContentsInDirectory(String path):能够将输入参数path所指定的本地磁盘路径下的所有目录和文件的名称打印出来;2)readContentsInDirectoryRecursive(String path):能够将输入参数path所指定的本地磁盘路径下的所有目录(包含所有子孙目录)和文件的名称以层次化结构打印出来。程序的输出如下所示。

import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String path = s.nextLine();
File f = new File(path);
int level = 0;
FileList fl = new FileList();
fl.readContentsInDirectory(f);
System.out.println("------------------");
fl.readContentsInDirectoryRecursive(f, level);
s.close();
}
}
class FileList
{
public void readContentsInDirectory(File path)
{
if(!path.exists())
{
System.out.println("路径"+path.getPath()+"不存在");
return ;
}
else
{
File[] f = path.listFiles();
for(int i = 0 ; i < f.length ; i++)
{
if(f[i].isFile())
{
System.out.println("[文件]"+f[i].getName());
}
else
{
System.out.println("[目录]"+f[i].getName());
}
}
}
}
public void readContentsInDirectoryRecursive(File path,int level)
{
if(!path.exists())
{
System.out.println("路径"+path.getPath()+"不存在");
return ;
}
else
{
File[] f = path.listFiles();
for(int i = 0 ; i < f.length ; i++)
{
for(int j = 0; j < level ; j++)
{
System.out.print("-");
}
if(f[i].isFile())
{
System.out.println("[文件]"+f[i].getName());
}
else
{
System.out.println("[目录]"+f[i].getName());
readContentsInDirectoryRecursive(f[i],level+2);
}
}
}
}
}
8-3 菜单文件处理 (20 分)
 

假设某个餐馆平时使用:1)文本文件(orders.txt)记录顾客的点菜信息,每桌顾客的点菜记录占一行。每行顾客点菜信息的记录格式是“菜名:数量,菜名:数量,…菜名:数量”。例如:“烤鸭:1,土豆丝:2,烤鱼:1”。2)文本文件(dishes.txt)记录每种菜的具体价格,每种菜及其价格占一行,记录格式为“菜名:价格“。例如:“烤鸭:169”。编写一个程序,能够计算出orders.txt中所有顾客消费的总价格。(注意,请使用文本读写流,及缓冲流来处理文件)

import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
BufferedReader br1 = null;
BufferedReader br2 = null;
List<Order> order = new ArrayList<>();
Map<String , Dish> dish = new HashMap<>();
try {
File f1 = new File("order.txt");
f1.createNewFile();
File f2 = new File("dishes.txt");
f2.createNewFile();
br1 = new BufferedReader(new FileReader("order.txt"));
br2 = new BufferedReader(new FileReader("dishes.txt"));
String S1 ;
while((S1 = br1.readLine()) != null)
{
String[] s1 = S1.split(",");
for(int i = 0 ; i < s1.length ; i++)
{
order.add(new Order(s1[0],Integer.parseInt(s1[1])));
}
}
String S2;
while((S2 = br2.readLine()) != null)
{
String[] s2 = S2.split(":");
dish.put(s2[0], new Dish(s2[0],Double.parseDouble(s2[1])));
}
double sum = 0;
for(int i = 0 ; i < order.size() ; i++)
{
sum += order.get(i).num * dish.get(i).price;
}
System.out.println(sum);
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br1 != null)
{
br1.close();
}
if(br2 != null)
{
br2.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
s.close();
}
}
class Order
{
public String name;
public int num;
public Order(String name, int num)
{
this.name = name;
this.num = num;
}
}
class Dish
{
public String name;
public double price;
public Dish(String name, double price)
{
this.name = name;
this.price = price;
}
}
8-4 成绩文件处理 (20 分)
 

设计学生类Student,属性:学号(整型);姓名(字符串),选修课程(名称)及课程成绩(整型)。编写一个控制台程序,能够实现Student信息的保存、读取。具体要求:(1)提供Student信息的保存功能:通过控制台输入若干个学生的学号、姓名以及每个学生所修课程的课程名和成绩,将其信息保存到data.dat中;(2)数据读取显示:能够从data.dat文件中读取学生及其课程成绩并显示于控制台。(要求,学号和课程成绩按照整数形式(而非字符串形式)存储)

import java.io.*;
import java.util.*; public class Test4 { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String l = null;
DataInputStream dis = null;
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("data.dat"));
while(!(l=sc.nextLine()).equals("exit")) {
String[] ss = l.split(" ");
Student s = new Student(Integer.parseInt(ss[0])
,ss[1],ss[2],Integer.parseInt(ss[3])); byte[] bs = s.getNameBytes();
byte[] cs = s.getCourseBytes(); dos.writeInt(s.no);
dos.writeInt(bs.length);
dos.write(bs);
dos.writeInt(cs.length);
dos.write(cs);
dos.writeInt(s.score);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dos.close();
}catch (IOException e) {
e.printStackTrace();
}
} try {
File f = new File("data.dat");
int size = (int) f.length();
int records = size/(4+4+(96+240)/8);
dis = new DataInputStream(new FileInputStream("data.dat")); while (true) {//for (int i=0;i<records;i++) {
int no = dis.readInt();
int bsize = dis.readInt();
byte[] bs = new byte[bsize];
dis.read(bs);
String name = new String(bs);
int wsize = dis.readInt();
byte[] ws = new byte[wsize];
dis.read(ws);
String course = new String(ws);
int score = dis.readInt();
System.out.println(no+" "+name+" "+course+" "+score);
}
} catch (EOFException e) {
System.out.println("end of file");
} catch (IOException e){
e.printStackTrace();
}finally {
try {
dis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
} } class Student {
int no;
String name;
String course;
int score; public byte[] getNameBytes() {
byte[] src = name.getBytes();
return src;
} public byte[] getCourseBytes(){
byte[] src = course.getBytes();
return src;
} public Student(int no, String name, String course, int score) {
super();
this.no = no;
this.name = name;
this.course = course;
this.score = score;
} }
8-5 图书馆持久化 (20 分)
 

构造图书类,包含名称(字符串)、作者(字符串)、出版社(字符串)、版本号(整数)、价格(浮点数),构造图书馆类,其中包含若干图书,用容器存储图书对象,然后定义方法void addBook(Book b)添加图书对象,定义方法void persist(),将所有图书存至本地文件books.dat里,定义方法Book[] restore() 从文件books,dat中读取所有图书,并返回图书列表数组。 main函数中构造图书馆类对象,向其中添加3个图书对象,测试其persist和restore方法。(注意,请使用对象序列化方法实现)

import java.io.*;
import java.util.ArrayList;
import java.util.List; public class Test5 {
/*构造图书类,包含名称(字符串)、作者(字符串)、出版社(字符串)、版本号(整数)、价格(浮点数),
* 构造图书馆类,其中包含若干图书,用容器存储图书对象,
* 然后定义方法void addBook(Book b)添加图书对象,
* 定义方法void persist(),将所有图书存至本地文件books.dat里,
* 定义方法Book[] restore() 从文件books,dat中读取所有图书,并返回图书列表数组。
* main函数中构造图书馆类对象,向其中添加3个图书对象,测试其persist和restore方法。
* (注意,请使用对象序列化方法实现)
*/ public static void main(String[] args) {
ObjectOutputStream oos = null;
Book[] bs = {
new Book ("Java","张峰", "清华大学出版社",2, 23.5),
new Book ("C++","刘冰", "清华大学出版社",2, 18),
new Book ("C","王莉", "清华大学出版社",2, 35)
};
Library l = new Library();
for (Book b : bs) {
l.addBook(b);
}
l.persist();
Book[] bs2 = l.restore();
for (Book b : bs) {
System.out.println(b);
}
} } class Book implements Serializable{
String name;
String author;
String press;
int edition;
double price; public Book(String name, String author, String press, int edition, double price) {
super();
this.name = name;
this.author = author;
this.press = press;
this.edition = edition;
this.price = price;
} @Override
public String toString() {
return "Book [name=" + name + ", author=" + author + ", press=" + press + ", edition=" + edition + ", price="
+ price + "]";
}
} class Library
{
List<Book> bs = new ArrayList<Book>(); public void addBook(Book b)
{
bs.add(b);
} public void persist ()
{
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream("books.dat"));
// 将per对象写入输出流
for(Book b :bs)
oos.writeObject(b);
}
catch (IOException ex)
{
ex.printStackTrace();
} finally {
try {
if (oos!=null)
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} public Book[] restore()
{
ObjectInputStream ois = null;
bs = new ArrayList<Book>();
try {
ois = new ObjectInputStream(
new FileInputStream("books.dat"));
//从输入流中读取一个Java对象,并将其强制类型转换为Person类
while (true)
{
Book b = (Book)ois.readObject();
bs.add(b);
}
}catch (EOFException e){
System.out.println("end of file");
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (ois!=null)
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Book[] ba = new Book[bs.size()];
bs.toArray(ba);
return ba;
} }
8-6 按行读文件 (20 分)
 

使用java的输入/输出流技术将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。

import java.io.*;
public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("in.txt"));
bw = new BufferedWriter(new FileWriter("out.txt"));
String s;
for(int i = 0 ; (s = br.readLine())!=null ; i++)
{
bw.write(i+" , "+s);
bw.newLine();
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
8-7 读写文件--程序设计 (20 分)
 

编写一个程序实现如下功能,文件fin.txt是无行结构(无换行符)的汉语文件,从fin中读取字符,写入文件fou.txt中,每40个字符一行(最后一行可能少于40个字) 请将程序代码贴到答案区内

import java.io.*;
public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("fin.txt"));
bw = new BufferedWriter(new FileWriter("out.txt"));
char[] c = new char[40];
int len = 40;
while((br.read(c, 0, len) )!= -1)
{
bw.write(c, 0, len);
bw.newLine();
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}

IO题目的更多相关文章

  1. 普及C组第四题(8.2)

    1342. [南海2009初中]cowtract(网络) (Standard IO) 题目:  Bessie受雇来到John的农场帮他们建立internet网络.农场有 N (2<= N < ...

  2. 普及C组第二题(8.2)

    1340. [南海2009初中]jumpcow(牛跳) (Standard IO) 题目: John的奶牛们计划要跳到月亮上去.它们请魔法师配制了 P (1 <= P <=150,000) ...

  3. NepCTF pwn writeup

    上周抽时间打了nepnep举办的CTF比赛,pwn题目出的挺不错的,适合我这种只会一点点选手做,都可以学到新东西. [签到] 送你一朵小红花 64位程序,保护全开. 程序会在buf[2]处留下一个da ...

  4. VS2015编译GEOS

    下载链接:http://trac.osgeo.org/geos/ 1. 打开cmake,加载geos源码和定位geos的工程存放位置: 2.点击configure,会报错,首先设置CMAKE_INST ...

  5. Linux硬件IO的优化简介

    Linux硬件IO的优化简介 首先简单介绍下有哪些硬件设备如下(由于硬件种类厂家等各种因素我就不在此多做介绍有兴趣的可以自行学习): 1.CPU:中央处理器,是计算机运算控制的核心部件之一,相当于人的 ...

  6. MMAP和DIRECT IO区别

    看完此文,题目不言自明.转自 http://blog.chinaunix.net/uid-27105712-id-3270102.html 在Linux 开发中,有几个关系到性能的东西,技术人员非常关 ...

  7. 看看国外的javascript题目,你能全部做对吗?

    叶小钗 的博客最近都在讨论面试题目 正好以前也看过一篇,就借花献佛拿出来分享一下 http://perfectionkills.com/javascript-quiz/ 附带了自己的理解,答案有争议的 ...

  8. PHP面试题目搜集

    搜集这些题目是想在学习PHP方面知识有更感性的认识,单纯看书的话会很容易看后就忘记. 曾经看过数据结构.设计模式.HTTP等方面的书籍,但是基本看完后就是看完了,没有然后了,随着时间的推移,也就渐渐忘 ...

  9. 经典.net面试题目

    1. 简述 private. protected. public. internal 修饰符的访问权限. 答 . private :   私有成员, 在类的内部才可以访问. protected : 保 ...

  10. 二十一、Java基础--------IO流之综合案例分析

    前三篇文章详细介绍了IO流体系所涉及的重点内容,为了帮助理解与学习,本片博客主要是分析一个与IO操作相关的题目. 例1:在我们观看视频时经常要关注的就是视频的时间长度,在学习了IO操作之后,就可以自己 ...

随机推荐

  1. 37.Spring注解相关面试题

    1.@Resource和@Autowired 区别 2.@Repository.@Component.@Service.@Controller 区别

  2. HTTP请求报文(请求行,请求头,请求体)

    HTTP协议 1.简介 HTTP协议(Hyper Text Transfer Protocol,超文本传输协议),是用于从万维网(WWW:World Wide Web )服务器传输超文本到本地浏览器的 ...

  3. iis express添加网站,并启动

    1.查看网站列表 C:\Program Files (x86)\Microsoft Visual Studio 12.0>"C:\Program Files\IIS Express\a ...

  4. bootstrap-treeview手动修改源码添加与后台交互的id

    bootstrap-treeview中只有自增的参数data-nodeid,没有id的参数,不方便后台交互,修改源码添加id. 1.图一为添加的自定义的node.Id; 2. 下图为添加的id 3.后 ...

  5. Docker之RabbitMQ保姆级别安装

    Docker之RabbitMQ保姆级别安装: 如果觉得样式不好:跳转即可 http://www.lifengying.site/(md文件复制过来有些样式会不一样) 学英语网站项目:自己先保证Redi ...

  6. 在Windows系统上安装和配置Jenkins自动发布

    一.安装jenkins的流程转载于: https://www.jianshu.com/p/de9c4f5ae7fa 二.在window中执行批处理文件bat或者powershell可以成功,但是Jen ...

  7. python菜鸟学习: 8. 集合基础知识

    # -*- coding: utf-8 -*-# 列表的特性:1,去重:2.关系测试list1 = [1, 4, 6, 8, 7, 8, 9]# 集合去重list2 = set(list1)print ...

  8. react+antd 开发一个可动态增减的复合组件

    需求如图: 与后端协商好的表单数据为: 组件代码: /* 阶梯分成组件 */ import React, { useState, useEffect } from 'react'; import { ...

  9. ES6 函数的扩展 rest参数

    function add(...values) { let sum = 0; for (var val of values) { sum += val; } return sum; } add(2, ...

  10. edge 浏览器部分功能

    模拟打印情况的调试