Java Tutorial/File/FileWriter

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Append or add some contents to the file

import java.io.File;
import java.io.FileWriter;
public class Main {
  public static void main(String[] args) throws Exception{
    File file = new File("user.txt");
    FileWriter writer = new FileWriter(file, true);
    writer.write("username=java;password=secret" + System.getProperty("line.separator"));
    writer.flush();
    writer.close();
  }
}





FileWriter

  1. FileWriter provides a convenient way of writing characters to a file.
  2. FileWriter uses your computer"s default character encoding.



public FileWriter (File file)
public FileWriter (File file, boolean append)
public FileWriter (String path)
public FileWriter (String path, boolean append)
public FileWriter (FileDescriptor fileDescriptor)





Use FileWriter to write an array of strings to a file.

import java.io.FileWriter;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileWriter fw = new FileWriter("file.dat");
    String strs[] = { "com", "exe", "doc" };
    for (int i = 0; i < strs.length; i++) {
      fw.write(strs[i] + "\n");
    }
    fw.close();
  }
}





Wrap FileWriter with BufferedWriter

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class AllCapsDemo {
  public static void main(String[] arguments) {
    String sourceName = "asdf";
    try {
      File source = new File(sourceName);
      File temp = new File("cap" + sourceName + ".tmp");
      FileReader fr = new FileReader(source);
      BufferedReader in = new BufferedReader(fr);
      FileWriter fw = new FileWriter(temp);
      BufferedWriter out = new BufferedWriter(fw);
      boolean eof = false;
      int inChar = 0;
      do {
        inChar = in.read();
        if (inChar != -1) {
          char outChar = Character.toUpperCase((char) inChar);
          out.write(outChar);
        } else
          eof = true;
      } while (!eof);
      in.close();
      out.close();
      boolean deleted = source.delete();
      if (deleted)
        temp.renameTo(source);
    } catch (Exception se) {
      System.out.println("Error - " + se.toString());
    }
  }
}