TP N° 10 : Gestion des fichiers Langage JAVA - Toubkal-it

Transcription

TP N° 10 : Gestion des fichiers Langage JAVA - Toubkal-it
TP N° 10 : Gestion des fichiers
Langage JAVA
Rappel :
Exemple d’utilisation de FileReader/FileWriter
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("in.txt");
File outputFile = new File("out.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
BufferedReader et PrintWriter
Utiles pour la lecture et l'écriture de fichiers textes.
BufferedReader in = new BufferedReader(new FileReader("in.txt"));
String str;
while ((str=in.readLine()) != null) {
// faire quelque chose avec la ligne
System.out.println(str);
}
in.close();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new FileWriter("in.txt"));
out.println(in.readLine().toLowerCase().toString());
out.println(in.readLine().toString());
out.close();
Page 1
M. LACHGAR Med
Exemple :
2
4
5
12
9
4
16
25
144
81
in.txt
out.txt
import java.io.*;
public class Copy {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("file/in.txt"));
PrintWriter out = new PrintWriter(new FileWriter("file/out.txt"));
String str;
while(((str = in.readLine()) != null)){
out.println((int)Math.pow(Integer.parseInt(str), 2));
}
out.close();
in.close();
} catch (FileNotFoundException e) {
System.out.println("Fichier introuvable");
} catch (IOException e) {
e.getMessage();
}
}
}
La classe File
Une classe qui permet de manipuler des fichiers et des répertoires sans toutefois accéder aux
données dans les fichiers.
File myFile = new File("file");
// Si on se trouve dans le répertoire courant
String relative = myFile.getPath(); // retourne "fichier.txt"
System.out.println(relative);
String absolute = myFile.getAbsolutePath();
System.out.println(absolute);
// C:\Users\lachgar\workspace\Exception\in.txt
System.out.println(absolute);
boolean there = myFile.exists(); // vrai ou faux si le fichier existe ou non
System.out.println(there);
boolean checkDir = myFile.isDirectory(); // si le fichier est un répertoire
System.out.println(checkDir);
long myLength = myFile.length(); // taille du fichier.
System.out.println(myLength);
// retourne les différents fichiers dans un répertoire
String[] allfiles = myFile.list();
for(String st : allfiles)
System.out.println(st);
Page 2
M. LACHGAR Med
ObjectInputStream et ObjectOutputStream


permettent de lire et écrire des objets sur un stream.
Un objet doit implémenter l'interface Serializable pour pouvoir être écrit ou lu.
L'interface Serializable contient les deux méthodes suivantes :
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream) throws IOException;
Exemple:
class Etudiant implements Serializable {
String nom;
String prenom;
double note;
Etudiant(String n, String p, double n) {
nom = n;
prenom = p;
note = n;
}
private void readObject(java.io.ObjectInputStream stream) {
nom = (String) stream.readObject();
prenom = (String) stream.readObject();
note = stream.readDouble();
}
private void writeObject(java.io.ObjectOutputStream stream) {
stream.writeObject(nom);
stream.writeObject(prenom);
stream.writeDouble(note);
}
}
Etudiant e = new Etudiant("salhi","samir",90);
FileOutputStream fos = new FileOutputStream("etd.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.close();
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
Etudiant e2 = (Etudiant) ois.readObject();
ois.close();
Page 3
M. LACHGAR Med
Problem A : Nombres opposés
Etant donné un tableau d'entiers non nuls, trouvez combien il y a d'entiers distincts positifs dont
l'opposé est aussi dans le tableau.
Par exemple, pour le tableau de taille 15 qui suit:
-3 4 2 8 9 1 -3 -8 -4 2 8 2 -8 1 3
il faut afficher 3. En effet, les trois entiers 3, 4, et 8 ont aussi leur opposé dans le tableau.
LIMITES DE TEMPS ET DE MEMOIRE (Langage : C++)
Temps : 1s sur une machine à 1Ghz.
Mémoire : 16000 Ko.
CONTRAINTES


1 <= N <= 20000, où N est le nombre d'éléments du tableau.
-10<SUP>8</SUP> < X < 10<SUP>8</SUP>, et X différent de 0, où X est un élément du
tableau.
De plus, dans 50% des tests, on a :

1 <= N <= 1000.
ENTRÉE


La première ligne de l'entrée contient un entier N, la taille du tableau.
La deuxième ligne contient N entiers séparés par des espaces : les éléments du tableau.
SORTIE
Vous devez écrire une ligne sur la sortie, contenant un entier K : le nombre d'entiers distincts X > 0,
tels que X et –X appartiennent tous les deux au tableau.
EXEMPLE
entrée :
15
-3 4 2 8 9 1 -3 -8 -4 2 8 2 -8 1 3
sortie :
3
Page 4
M. LACHGAR Med
Solution :
import
import
import
import
import
java.io.*;
java.util.Iterator;
java.util.Set;
java.util.StringTokenizer;
java.util.TreeSet;
public class ProblemeA {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("file/in.txt"));
PrintWriter out = new PrintWriter(new FileWriter("file/out.txt"));
int n = Integer.parseInt(in.readLine().toString());
StringTokenizer st = new StringTokenizer(in.readLine()," ");
Set <Integer> set = new TreeSet<Integer>();
Set <Integer> set2 = new TreeSet<Integer>();
while(st.hasMoreElements()){
set.add(Integer.parseInt(st.nextElement().toString()));
}
int size1 = set.size();
Iterator<Integer> it = set.iterator();
while(it.hasNext()){
set2.add(Math.abs(it.next()));
}
out.println(size1 - set2.size());
out.close();
in.close();
}
}
Page 5
M. LACHGAR Med
Problem B – Binary Addition
Source file: bin.c | bin.cpp | bin.java, Input file: bin.in, output file: bin.out
Problem Description
Adding binary numbers is a very simple task, and very similar to the longhand addition of
decimal numbers. As with decimal numbers, you start by adding the bits (digits) one column at a
time, from right to left. Unlike decimal addition, there is little to memorize in the way of rules for
the addition of binary bits:
0+0=0
1+0=1
0+1=1
1 + 1 = 10
1 + 1 + 1 = 11
Just as with decimal addition, when the sum in one column is a two-bit (two-digit) number. the
least significant figure is written as part of the total sum and the most significant figure is "carried"
to the next left column. Consider the following examples:
11 1
<-- Carry bits -->
1 11
1001101
1001001
1000111
+ 0010010
+ 0011001
+ 1010110
------------------------1011111
1100010
10011101
The addition problem on the left did not require any bits to be carried, since the sum of bits in
each column was either 1 or 0, not 10 or 11. In the other two problems, there definitely were bits
to be carried, but the process of addition is still quite simple.
Input Specifications
The first line of input contains an integer N, (1 <= N <= 1000), which is the number of binary
addition problems that follow. Each problem appears on a single line containing two binary
values separated by a single space character. The maximum length of each binary value is 80 bits
(binary digits). Note: The maximum length result could be 81 bits (binary digits).
Output Specifications
For each binary addition problem, print the problem number, a space, and the binary result of the
addition. Extra leading zeroes must be omitted.
Sample Input/Output
bin.in
3
1001101 10010
1001001 11001
1000111 1010110
bin.out
1 1011111
2 1100010
3 10011101
Page 6
M. LACHGAR Med
Solution :
import
import
import
import
import
import
import
java.io.BufferedReader;
java.io.FileReader;
java.io.FileWriter;
java.io.IOException;
java.io.PrintWriter;
java.math.BigInteger;
java.util.StringTokenizer;
public class Bin {
public static void main(String[] args) throws NumberFormatException, IOException {
int N,i, var = 0;
BigInteger a, b;
StringTokenizer st = null;
BufferedReader in = new BufferedReader(new FileReader("bin.in"));
PrintWriter out = new PrintWriter (new FileWriter("bin.out"));
N = Integer.parseInt(in.readLine());
for( i = 1 ; i <= N ; i++)
{
st = new StringTokenizer(in.readLine());
st.hasMoreTokens();
a = new BigInteger(st.nextToken(), 2);
b = new BigInteger(st.nextToken(), 2);
if (var !=0) out.println("");
var = 1;
out.print(i+" "+a.add(b).toString(2));
}
in.close();
out.close();
}
}
Page 7
M. LACHGAR Med
Problem B – Good triangle
Source file: good.c | good.cpp | good.java, Input file: good.in, output file: good.out
Problem Description
The nth Triangular number, T(n) = 1 + ... + n, is the sum of the first n integers. It is the number of
points in a triangular array with n points on side. For example T(4):
Write a program to compute the weighted sum of triangular numbers: W (n) = SUM[k = 1..n;
k*T(k+1)]
Input Specifications
The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that
follow.
Each dataset consists of a single line of input containing a single integer n, (1 ≤ n ≤300), which is the
number of points on a side of the triangle.
Output Specifications
For each dataset, output on a single line the dataset number, (1 through N), a blank, the value of n
for the dataset, a blank, and the weighted sum: W (n), of triangular numbers for n.
Sample Input/Output
good.in
4
3
4
5
10
good.out
1
2
3
4
Page 8
3 45
4 105
5 210
10 2145
M. LACHGAR Med
Solution :
import
import
import
import
import
java.io.BufferedReader;
java.io.FileReader;
java.io.FileWriter;
java.io.IOException;
java.io.PrintWriter;
public class Good {
static int T(int n)
{
int i,s = 0;
for(i = 1;i <= n; i++)
s+= i;
return s;
}
static int w(int n)
{
int s = 0,k;
for(k = 1;k <= n;k++)
{
s+= k * T(k + 1);
}
return s;
}
public static void main(String[] args) throws NumberFormatException, IOException {
int N,n,i, var = 0;
BufferedReader in = new BufferedReader(new FileReader("good.in"));
PrintWriter out = new PrintWriter (new FileWriter("good.out"));
N = Integer.parseInt(in.readLine());
for( i = 1 ; i <= N ; i++)
{
n = Integer.parseInt(in.readLine());
if (var !=0) out.println("");
var = 1;
out.print(i+" "+n+" "+w(n));
}
in.close();
out.close();
}
}
Page 9
M. LACHGAR Med

Documents pareils

Exemple d`utilisation de FileReader/FileWriter

Exemple d`utilisation de FileReader/FileWriter File myFile = new File("/u/user/ift6810/fichier.txt"); // Si on se trouve dans le répertoire /u/user/ift6810 String relative = myFile.getPath(); // retourne "fichier.txt" String absolute = myFile.g...

Plus en détail