En este ejemplo se crea el archivo "archivo.tmp" y se le escribe información de dos formas diferentes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
public class ArchivoTemporal | |
{ | |
public static void main(String[] args) | |
{ | |
try{ | |
//Crear un archivo temporal | |
File temp = File.createTempFile("archivo", ".tmp"); | |
//Le indicamos que lo eleminte cuando se cierre el programa. | |
temp.deleteOnExit(); | |
//Escribir contenido con BufferedWriter | |
BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); | |
bw.write("This is the temporary file content"); | |
bw.close(); | |
/*¨--- ALTERNATIVA ---*/ | |
//Escribir el archivo con un InputStream | |
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/pack/yourfile"); | |
FileOutputStream outputStream = new FileOutputStream(file); | |
int read = 0; | |
byte[] bytes = new byte[is.available()]; | |
while ((read = is.read(bytes)) != -1) { | |
outputStream.write(bytes, 0, read); | |
} | |
is.close(); | |
outputStream.close(); | |
}catch(IOException e){ | |
e.printStackTrace(); | |
} | |
} | |
} |
No hay comentarios :
Publicar un comentario