Advertisement
Guest User

Untitled

a guest
Apr 24th, 2015
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. import java.io.*;
  2. public class ficheros{
  3.     public static void main(String[] args) throws IOException{  //evitamos que nos salten excepciones, normalmente usariamos try-catch para capturarlas
  4.         File path=new File("trabajo");
  5.         System.out.println(path.getAbsolutePath());
  6.         File f=new File(path, "prueba.txt");
  7.         System.out.println(f.getAbsolutePath());
  8.         if(path.mkdir()){
  9.             System.out.println("El directorio: \"" + path.getName() + "\" creado correctamente");
  10.             if(f.createNewFile()){
  11.                 System.out.println("El fichero: \"" + f.getName() + "\" creado correctamente");
  12.             }
  13.  
  14.         }
  15.         if(f.exists()){
  16.         System.out.println("El fichero: \"" + f.getName() + "\" existe");
  17.  
  18.         }
  19.         String[] dir = path.list();
  20.         System.out.print("Contenido del directorio: ");
  21.         for(String nameFile : dir){
  22.             System.out.println(nameFile);
  23.         }
  24.        
  25.         PrintWriter output = new PrintWriter(f);
  26.         for(int i = 0; i<10;i++){
  27.             output.println("linea: " + i);
  28.         }
  29.         output.close();     //hay que cerrar el fichero para que la info este disponible
  30.         System.out.println(f.length());
  31.        
  32.         FileReader input = new FileReader(f);   //leer fichero f
  33.         int c = input.read();
  34.         while(c!=-1){        //leerlo todo byte a byte, -1 detecta fin de fichero
  35.             System.out.print((char)c);  //te lo da en ascci, le fices que sea char y lo pasa solo
  36.             c=input.read();
  37.         }
  38.         input.close();
  39.        
  40.         FileWriter fw = new FileWriter(f, true);    //fichero donde escribimos y si true añade, si false trunca
  41.         output=new PrintWriter(fw);
  42.         for(int i = 10; i<20;i++){
  43.             output.println("linea: " + i);
  44.         }
  45.         output.close();
  46.         System.out.println(f.length());
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement