
- •Лабораторная работа № 3 Обработка файлов
- •Введение
- •Класс InputStream
- •Класс OutputStream
- •Файловый ввод/вывод
- •Буферизованные потоки
- •Класс File
- •Класс RandomAccessFile
- •Пример подсчета количества определенного слова в файле
- •Пример объекта "Книга" с методами чтения и записи в файл
- •Работа с конфигурационными файлами
- •Пример класса preloader для загрузки конфигурационного файла
- •Контрольные вопросы
- •Задание
- •Приложение 1. Работа с датой и временем в Java
- •Приложение 2. Класс StreamTokenizer
Пример подсчета количества определенного слова в файле
Пусть необходимо разработать программу, подсчитывающую количество определенного слова в файле. В качестве параметров в командной строке передаются:
имя файла
кодировка файла
слово для подсчета
import java.io.*;
import java.util.Scanner;
public class Reader {
private static String _encoding;
private static String _string;
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Wrong number of input arguments");
return;
}
File testFile = new File(args[0]);
_encoding = args[1];
_string1 = args[2];
String contents = GetContents(testFile);
System.out.print("File contents:\r\n" + contents);
System.out.println("--------------------------------------------");
Analyze(contents);
}
static public String GetContents(File file){
StringBuilder contents = new StringBuilder();
try {
if (file == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!file.exists()) {
throw new FileNotFoundException();
}
if (!file.canRead()) {
throw new IllegalArgumentException("File cannot be written: " + file);
}
if (!file.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + file);
}
FileInputStream fis = new FileInputStream(file);
InputStreamReader in = new InputStreamReader(fis, _encoding);
BufferedReader input = new BufferedReader(in);
try {
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line + "\r\n");
}
}
finally {
input.close();
}
} catch (FileNotFoundException ex) {
System.out.println("File does not exist: " + file);
} catch(IllegalArgumentException ex) {
System.out.println(ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
}
return contents.toString();
}
private static void Analyze(String contents) {
Scanner scanner = new Scanner(contents);
int stringCount = 0;
while (scanner.hasNextLine()) {
Scanner s = new Scanner(scanner.nextLine());
while (s.hasNext()) {
String word = s.next();
if (word.contentEquals(_string))
stringCount++;
}
s.close();
}
scanner.close();
System.out.println(_string + " — " + stringCount);
}
}
Пример объекта "Книга" с методами чтения и записи в файл
Свойствами объекта «Книга» (book) являются:
Название - Name
Аннотация - Annot
Автор - Author
Язык - Lang
Издательство - Publisher
Количество страниц - Size
Дата выхода - DateOutput
package study;
import java.util.Map;
import study.abstracts.*;
import java.io.*;
import java.time.LocalDate;
public class book extends material {
book() {
super();
}
book(Map <Integer, String> errListTemp) {
super(errListTemp);
}
/**
* Добавляем поля объекта в файл
* @param FileName имя файла с путем
* @param Update: true или false
* @return boolean
* @throws FileNotFoundException
*/
public boolean saveToFile(String FileName, boolean Update) throws java.io.IOException {
boolean Result = false;
FileWriter dataOut = null;
try{
dataOut = new FileWriter(FileName, Update);
dataOut.append(this.toString());
Result = true;
}
catch( IOException exc ) {
System.err.println(exc.getMessage());
}
finally {
dataOut.close();
}
return Result;
}
public boolean getFromFile(String FileName) {
boolean Result = false;
String temp = "";
String key = "";
String value = "";
boolean start = false;
try{
FileReader fr = new FileReader(FileName);
char a = (char) fr.read(); //Читаем один символ
//Читаем
BufferedReader br = new BufferedReader(new FileReader(FileName));
while((temp = br.readLine()) != "" & temp != null) {
if( temp.indexOf("book::") >= 0 ) {
//Устанавливаем признак начала разбора строк
start = true;
}
else if( temp.length() == 0 ) {
start = false;
}
if( start ) {
key = temp.substring(0, temp.indexOf(':'));
value = temp.substring(temp.indexOf(':')+2,temp.length()-1);
if( !key.isEmpty() && !value.isEmpty()) {
switch (key) {
case "Name":
this.setName(value);
break;
case "Annot":
this.setAnnot(value);
break;
case "Author":
this.setAuthor(value);
break;
case "Publisher":
this.setPublisher(Integer.parseInt(value));
break;
case "Lang":
this.setLang(value);
break;
case "Size":
this.setSize(Integer.parseInt(value));
break;
case "DateOutput":
this.setDateOutput(LocalDate.parse(value));
break;
}
}
}
}
br.close();
}
catch( IOException exc ) {
System.out.println(exc.getMessage());
}
return Result;
}
public String toString() {
String Result = "book::;\r\n";
Result += "Name: "+this.getName()+";\r\n";
Result += "Annot: "+this.getAnnot()+";\r\n";
Result += "Lang: "+this.getLang()+";\r\n";
Result += "Author: "+this.getAuthor()+";\r\n";
Result += "Publisher: "+this.getPublisher()+";\r\n";
Result += "Size: "+this.getSize()+";\r\n";
Result += "DateOutput: "+this.getDateOutput()+";\r\n\r\n";
return Result;
}
}