Электронная библиотека книг Александра Фролова и Григория Фролова.
Shop2You.ru Создайте свой интернет-магазин
Библиотека
Братьев
Фроловых
[Назад]

Исходный текст программы FileOperations.java

Оглавление

Назад

// ==========================================
// FileOperations.java
// (C) Alexandr Frolov, 1998
// E-mail: frolov@glasnet.ru
// Web:    http://www.glasnet.ru/~frolov 
// ==========================================
import java.io.*;
import java.util.*;

public class FileOperations 
{
  // ============================================
  // main
  // ============================================
  public static void main(String args[])
  {
    int i;
    
    System.out.println(
      "* File control demonstration\n");

    try
    {  
      File f = new File("!temp.txt");
      FileOutputStream fos = 
        new FileOutputStream(f);
      DataOutputStream dos = 
        new DataOutputStream(fos);
      
      for(i = 0; i < 10; i++)
         dos.writeBytes("Test");
      dos.close();      

      System.out.println("Absolute path: " +
	f.getAbsolutePath());

      System.out.println("Canonical path: " +
	f.getCanonicalPath());
	
      System.out.println("Length: " +
	f.length());

      File f1 = new File("!temp1.txt");
      
      if(!f.renameTo(f1))
        System.out.println("Rename failed");
        
      FileInputStream fis = 
	new FileInputStream("!temp1.txt");
	
      FileOutputStream fos1 = 
	new FileOutputStream("output.txt");
	
      fileCopy(fis, fos1);	
      
      if(!f1.delete())
        System.out.println("Delete failed");
      
      System.out.println("Done!");
    }
    catch(Exception ex)
    {
      System.out.println(ex.toString());
    }
  }
  
  // ============================================
  // fileCopy
  // ============================================
  public static void fileCopy(InputStream is, 
    OutputStream os) throws IOException
  {
    int nLength;
    byte[] buf = new byte[8000];
    while(true)
    {
      nLength = is.read(buf);
        if(nLength < 0) 
	   break;
      os.write(buf, 0, nLength);
    }
       
    is.close();
    os.close();
  }  
}

[Назад]