Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.devcolibri.tools;
- import java.io.*;
- public class FileWorker {
- public static void write(String fileName, String textFromFile) {
- File file = new File(fileName);
- try {
- if(!file.exists()){
- file.createNewFile();
- }
- PrintWriter out = new PrintWriter(file.getAbsoluteFile());
- try {
- out.print(textFromFile);
- } finally {
- out.close();
- }
- } catch(IOException e) {
- throw new RuntimeException(e);
- }
- }
- public static String read(String fileName) throws FileNotFoundException {
- StringBuilder sb = new StringBuilder();
- File file = new File(fileName);
- exists(fileName);
- try {
- BufferedReader in = new BufferedReader(new FileReader( file.getAbsoluteFile()));
- try {
- String s;
- while ((s = in.readLine()) != null) {
- sb.append(s);
- sb.append("\r\n");
- }
- } finally {
- in.close();
- }
- } catch(IOException e) {
- throw new RuntimeException(e);
- }
- return sb.toString();
- }
- public static void update(String nameFile, String newText) throws FileNotFoundException {
- exists(nameFile);
- StringBuilder sb = new StringBuilder();
- String oldFile = read(nameFile);
- sb.append(oldFile);
- sb.append(newText);
- write(nameFile, sb.toString());
- }
- public static void delete(String nameFile) throws FileNotFoundException {
- exists(nameFile);
- new File(nameFile).delete();
- }
- private static void exists(String fileName) throws FileNotFoundException {
- File file = new File(fileName);
- if (!file.exists()){
- throw new FileNotFoundException(file.getName());
- }
- }
- }
- package com.devcolibri.core;
- import com.devcolibri.tools.FileWorker;
- import java.io.FileNotFoundException;
- /**
- * User: devcolibri.com
- */
- public class WorkInFile {
- private static String text = "This new text2\nThis new text3\nThis new text4\n";
- private static String fileName = "D://Current tasks//STT//meeting_negotiations_corpus_material//info_files//1406901600000.info";
- private static String fileNameFinal = "D://Current tasks//STT//meeting_negotiations_corpus_material//info_files//1406901600000.info";
- public static void main(String[] args) throws FileNotFoundException {
- //Чтение файл
- String textFromFile = FileWorker.read(fileName);
- System.out.println(textFromFile);
- //Запись в файл
- FileWorker.write(fileNameFinal, textFromFile);
- //Обновление файла
- FileWorker.update(fileNameFinal, "This new text");
- //Попытка прочитать не существующий файл
- //FileWorker.read("no_file.txt");
- //Удаление файла
- // FileWorker.delete(fileName);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement