Files
Due semplici classi Java grezze per l’interazione con i file.
Make File
import java.io.*; public class make_file { private String nomefile; private File newFile; public make_file(String nomefile) { this.nomefile = nomefile; this.newFile = new File(this.nomefile); } public int getLength() throws IOException{ //Return the number of rows FileInputStream is = new FileInputStream(newFile); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int i=0; String s = br.readLine(); if (s != null){ i = 1; } else return i; while (s != null) { s = br.readLine(); i++; } return i-1; } public long getByteLength() { //Return the file byte dimension return newFile.length(); } public String[] getFile() throws IOException { //Return an String array that contain the file rows FileInputStream is = new FileInputStream(newFile); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String[] vettFile = new String[getLength()]; String s = br.readLine(); int i = 0; while(s !=null){ vettFile[i] = s; s = br.readLine(); i++; } return vettFile; } public void copia(String dest) throws IOException { //Copy the current file in a new file called "dest" FileInputStream is = new FileInputStream(newFile); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); File f1 = new File(dest); FileOutputStream fos = new FileOutputStream(f1); PrintStream pr = new PrintStream(fos); copia1(br,pr); fos.close(); } private static void copia1(BufferedReader br, PrintStream pr) throws IOException { String s = br.readLine(); if (s != null) { pr.println(s); copia1(br,pr); } } public void setFile(String[] input) throws IOException { //[Riempie] file with an array input string FileOutputStream fos; if(newFile.exists()){ fos = new FileOutputStream(newFile, true); } else { fos = new FileOutputStream(newFile); } PrintStream pr = new PrintStream(fos); for(int i = 0; i< input.length; i++) { //pr.println(input[i]); pr.append(input[i]); pr.append('\n'); } pr.append("Ciao"+'\n'); fos.close(); } }
Client File
import java.io.*; import javax.swing.JOptionPane; public class client_make_file { public static void main(String[] args) throws IOException { make_file a = new make_file("prova.txt"); String[] input = new String[10]; String[] ritorno = new String[a.getLength()]; for (int i = 0; i<10; i++){ input[i] = JOptionPane.showInputDialog(null,"inserisci un valore"); } a.setFile(input); System.out.println("Lunghezza "+a.getLength()); System.out.println("Lunghezza in byte "+a.getByteLength()); ritorno = a.getFile(); System.out.println("Valori di ritorno"); for (int i = 0; i<ritorno.length; i++){ System.out.println(ritorno[i]); } a.copia("copiaprova.txt"); } }
Commenti recenti