• No results found

TP N 10 : Gestion des fichiers Langage JAVA

N/A
N/A
Protected

Academic year: 2021

Share "TP N 10 : Gestion des fichiers Langage JAVA"

Copied!
9
0
0

Loading.... (view fulltext now)

Full text

(1)

TP N° 10 : Gestion des fichiers

Langage JAVA

Rappel :

Exemple d’utilisation de FileReader/FileWriter

BufferedReader et PrintWriter

Utiles pour la lecture et l'écriture de fichiers textes.

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 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();

(2)

Exemple :

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);

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();

} }

}

2 4 5 12 9

4 16 25 144 81

in.txt out.txt

(3)

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();

(4)

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

(5)

Solution :

import java.io.*;

import java.util.Iterator;

import java.util.Set;

import java.util.StringTokenizer;

import 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();

} }

(6)

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 bin.out

3

1001101 10010 1001001 11001 1000111 1010110

1 1011111 2 1100010 3 10011101

(7)

Solution :

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.math.BigInteger;

import 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();

} }

(8)

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 good.out

4 3 4 5 10

1 3 45 2 4 105 3 5 210 4 10 2145

(9)

Solution :

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import 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();

} }

References

Related documents

Magic Words to Selling and Sponsoring Copyright 2012 ~ Sonia Stringer and Savvy Biz Solutions Inc Page 7 Classic Mistake #2 – We Talk ABOUT the Products or Business

1.4.10 If the serum bilirubin level falls during intensified phototherapy to a level 50 micromol/litre below the threshold for which exchange transfusion is indicated reduce

In the city of Borken, county of Kassel, and city of Essen, the administrations, public and private or- ganizations, and private citizens alike managed various challenges, such

Burden of Arrhythmias in Epilepsy Patients: A Nationwide Burden of Arrhythmias in Epilepsy Patients: A Nationwide Inpatient Analysis of 1.4 Million Hospitalizations in the United

Previously, she served as the chief of Internal Audit for the Ohio Bureau of Workers Compensation; assistant deputy director of fiscal services for the Ohio Job and Family

If it succeeds, we have proved non-termination of the original program, and the edge-closing quasi-invariants of the SCSG and the trace given by the reachability checker form

hospital) audit began with records from FY05-06. Myers &amp; Stauffer is the contractor who sent surveys to hospitals to get information collected and reported. They are

El atesoramiento de vasos griegos y su deposi- ción en contextos incompatibles con su cronología de producción no es del todo un fenómeno desco- nocido en la Península