TP N 10 : Gestion des fichiers Langage JAVA



Similar documents
TP1 : Correction. Rappels : Stream, Thread et Socket TCP

Licence Informatique Année Exceptions

POB-JAVA Documentation

Langages Orientés Objet Java

Brazil + JDBC Juin 2001, douin@cnam.fr

Input / Output Framework java.io Framework

TP : Système de messagerie - Fichiers properties - PrepareStatement

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

D06 PROGRAMMING with JAVA

Thursday, February 7, DOM via PHP

What is an I/O Stream?

13 File Output and Input

Remote Method Invocation

CS 1302 Ch 19, Binary I/O

Introduction. GEAL Bibliothèque Java pour écrire des algorithmes évolutionnaires. Objectifs. Simplicité Evolution et coévolution Parallélisme

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Creating a Simple, Multithreaded Chat System with Java

ExempleRMI.java. // Fichier de defintion des droits et proprietes // System.setProperty("java.security.policy","../server.java.

Annexe - OAuth Introduction. Xavier de Rochefort xderoche@labri.fr - labri.fr/~xderoche 15 mai 2014

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Note concernant votre accord de souscription au service «Trusted Certificate Service» (TCS)

Object-Oriented Programming in Java

Calcul parallèle avec R

INPUT AND OUTPUT STREAMS

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Cours de Java. Sciences-U Lyon. Java - Introduction Java - Fondamentaux Java Avancé.

Course Intro Instructor Intro Java Intro, Continued

HEALTH CARE DIRECTIVES ACT

Files and input/output streams

WRITING DATA TO A BINARY FILE

Programming in Java

Lesson: All About Sockets

Solutions Premiers Pas

Liste d'adresses URL

Event-Driven Programming

public static void main(string[] args) { System.out.println("hello, world"); } }

Méthodes ensemblistes pour une localisation robuste de robots sous-marins

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

JAVA - FILES AND I/O

«Object-Oriented Multi-Methods in Cecil» Craig Chambers (Cours IFT6310, H08)

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Using Files as Input/Output in Java 5.0 Applications

Personnalisez votre intérieur avec les revêtements imprimés ALYOS design

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Introduction au BIM. ESEB Seyssinet-Pariset Economie de la construction contact@eseb.fr

CS506 Web Design and Development Solved Online Quiz No. 01

Sélection adaptative de codes polyédriques pour GPU/CPU

niveau : 1 ere année spécialité : mécatronique & froid et climatisation AU : Programmation C Travaux pratiques

Tool & Asset Manager 2.0. User's guide 2015

CSS : petits compléments

In-Home Caregivers Teleconference with Canadian Bar Association September 17, 2015

We are pleased to present you with detailed instructions on processing your visa application with us. Within this information pack you will find:

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Building a Multi-Threaded Web Server

"Internationalization vs. Localization: The Translation of Videogame Advertising"

Technical Service Bulletin

TP JSP : déployer chaque TP sous forme d'archive war

Short Form Description / Sommaire: Carrying on a prescribed activity without or contrary to a licence

General Certificate of Education Advanced Level Examination June 2012

Cours. Client/serveur avancé en Java (servlets, RMI, etc.) M.M.F.A.I. François Bourdoncle

Office of the Auditor General / Bureau du vérificateur général FOLLOW-UP TO THE 2010 AUDIT OF COMPRESSED WORK WEEK AGREEMENTS 2012 SUIVI DE LA

MR-(Mapreduce Programming Language)

Unrealized Gains in Stocks from the Viewpoint of Investment Risk Management

Detection of water leakage using laser images from 3D laser scanning data

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Une campagne de sensibilisation est lancée (1) pour lutter (1) contre les conséquences de l'alcool au volant. Il faut absolument réussir (2).

Stream Classes and File I/O

Hours: The hours for the class are divided between practicum and in-class activities. The dates and hours are as follows:

Future Entreprise. Jean-Dominique Meunier NEM Executive Director Nov. 23, 2009 FIA Stockholm

Etudes de cas en OCL avec l outil USE 2

Chapter 2: Elements of Java

Audit de sécurité avec Backtrack 5

ACP-EU Cooperation Programme in Science and Technology (S&T II) / Programme de Coopération ACP-UE pour la Science et la Technologie

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Sun Management Center Change Manager Release Notes

ATP Co C pyr y ight 2013 B l B ue C o C at S y S s y tems I nc. All R i R ghts R e R serve v d. 1

TIMISKAMING FIRST NATION

Pro3 1 : listes chaînées

TP : Configuration de routeurs CISCO

Optimizing and interfacing with Cython. Konrad HINSEN Centre de Biophysique Moléculaire (Orléans) and Synchrotron Soleil (St Aubin)

System Requirements Orion

Formation à l ED STIC ED STIC Doctoral education. Hanna Klaudel

Aucune validation n a été faite sur l exemple.

Regulatory Compliance Statement

TOURIST VISA REQUIREMENTS GHANA (Multiple Entry), TOGO and BENIN

Memory Eye SSTIC Yoann Guillot. Sogeti / ESEC R&D yoann.guillot(at)sogeti.com

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

sept-2002 Computer architecture and software cells for broadband networks Va avec

STUDENT APPLICATION FORM (Dossier d Inscription) ACADEMIC YEAR (Année Scolaire )

READ AND FOLLOW ALL SAFETY INSTRUCTIONS 1. DANGER RISK OF SHOCK DISCONNECT POWER BEFORE INSTALLATION

Tanenbaum, Computer Networks (extraits) Adaptation par J.Bétréma. DNS The Domain Name System

Transcription:

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

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

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

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

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

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 1 1011111 2 1100010 3 10011101 bin.out Page 6

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

Problem B Good triangle Source file: good.c good.cpp good.java, Input file: good.in, output file: good.out Problem Description The n th 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 4 3 4 5 10 good.in 1 3 45 2 4 105 3 5 210 4 10 2145 good.out Page 8

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