Obraz zawierający tekst, Czcionka, Grafika

Opis wygenerowany automatycznie 

Kierunek Informatyka

 

Instrukcja do ćwiczeń laboratoryjnych nr:

12

Nazwa przedmiotu:
Programowanie w języku Java

Temat: Operacje na plikach

Tryb studiów: stacjonarne

Czas trwanie ćw.

2x45 min

Autor materiałów: dr Marcin Skuba

 

1. Treści programowe:

Strumienie plikowe . Zapisywanie danych do pliku, odczytywanie danych z pliku. Strumienie znakowe i bajtowe. Obsługa wyjątków w javie – instrukcja trycatch.

2.      Cel zajęć:

Poznanie mechanizmów operujących na strumieniach danych. Opanowanie umiejętności zapisywania i odczytwania danych z/do pliku na dysku.

 

3. Materiały

Program odczytujący dane z pliku tekstowego:

 

import java.io.File;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.util.Scanner;

public class
OdczytTekstuZPliku {
   
public static void main(String[] args) {
        String tekst=
"";

        try
{
            File file =
new File("tekst.txt");
           
String absolutePath = file.getAbsolutePath();
           
Scanner scanner = new Scanner(new FileInputStream(absolutePath),"UTF-8");

               
// sprawdzanie czy linia tekstu istnieje
           
while(scanner.hasNextLine()){
                tekst+=scanner.nextLine()+
"\n";
           
}
        }
catch (FileNotFoundException e) {
            e.printStackTrace()
;
       
}
        System.out.println(tekst)
;
   
}
}

 

 

 

Program zapisujący dane tekstowe do pliku txt:

 

import java.io.*;
 
public class ZapisTekstuDoPliku {
 
    public static void main(String[] args) {
        try {
              File file = new File("dane.txt");
              FileWriter out = new FileWriter(file);
 
            String tekst = "Dane tekstowe zapisane do pliku";
            out.write(tekst);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

Przykład aplikacji wykorzystującej strumienie znakowe do zapisywania i odczytywania danych do/z pliku:

 

import javax.swing.*;
import
javax.swing.filechooser.FileNameExtensionFilter;
import
java.awt.*;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.io.*;
import
java.util.Scanner;

public class
Notatki extends JFrame implements ActionListener{
    JTextArea
textArea;
   
JMenuItem menuItemZamknij, menuItemKopiuj, menuItemWklej, menuItemInfo, menuItemSave, menuItemOpen, menuItemNew;
   
JButton buttonZamknij, buttonKopiuj, buttonWklej, buttonInfo, buttonSave, buttonOpen, buttonNew;

   
Notatki(){
        
super("Notatki");
       
setSize(800,800);
       
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width  - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);
       
Image imageIconFrame = new ImageIcon(getClass().getClassLoader().getResource("ikona_logo.png")).getImage();
       
setIconImage(imageIconFrame);
       
JPanel panelG = new JPanel(new BorderLayout());
       
textArea = new JTextArea();
       
JScrollPane jScrollPane = new JScrollPane(textArea);
       
panelG.add(jScrollPane, BorderLayout.CENTER);
       
JToolBar pasek = new JToolBar();

       
ImageIcon imageIconZamknij = new ImageIcon(getClass().getClassLoader().getResource("close.png"));
       
ImageIcon imageIconKopiuj = new ImageIcon(getClass().getClassLoader().getResource("copy.png"));
       
ImageIcon imageIconWklej = new ImageIcon(getClass().getClassLoader().getResource("paste.png"));
       
ImageIcon imageIconInfo = new ImageIcon(getClass().getClassLoader().getResource("info.png"));
       
ImageIcon imageIconSave = new ImageIcon(getClass().getClassLoader().getResource("save.png"));
       
ImageIcon imageIconOpen = new ImageIcon(getClass().getClassLoader().getResource("open.png"));
       
ImageIcon imageIconNew = new ImageIcon(getClass().getClassLoader().getResource("new.png"));

       
buttonNew = new JButton(imageIconNew);
       
buttonNew.addActionListener(this);
       
pasek.add(buttonNew);

       
buttonSave = new JButton(imageIconSave);
       
buttonSave.addActionListener(this);
       
pasek.add(buttonSave);

       
buttonOpen = new JButton(imageIconOpen);
       
buttonOpen.addActionListener(this);
       
pasek.add(buttonOpen);

       
pasek.addSeparator();
       
buttonZamknij = new JButton(imageIconZamknij);
       
buttonZamknij.addActionListener(this);
       
pasek.add(buttonZamknij);

       
buttonKopiuj = new JButton(imageIconKopiuj);
       
buttonKopiuj.addActionListener(this);
       
pasek.add(buttonKopiuj);

       
buttonWklej = new JButton(imageIconWklej);
       
buttonWklej.addActionListener(this);
       
pasek.add(buttonWklej);

       
buttonInfo = new JButton(imageIconInfo);
       
buttonInfo.addActionListener(this);
       
pasek.add(buttonInfo);

       
panelG.add(pasek, BorderLayout.NORTH);

       
JMenuBar jMenuBar = new JMenuBar();
       
JMenu menuPlik = new JMenu("Plik");
       
JMenu menuEdycja = new JMenu("Edycja");
       
JMenu menuInfo = new JMenu("Informacje");
       
jMenuBar.add(menuPlik);
       
jMenuBar.add(menuEdycja);
       
jMenuBar.add(menuInfo);

       
menuItemZamknij = new JMenuItem("Zamknij", imageIconZamknij);
       
menuItemKopiuj = new JMenuItem("Kopiuj", imageIconKopiuj);
       
menuItemWklej = new JMenuItem("Wklej", imageIconWklej);
       
menuItemInfo = new JMenuItem("O programie", imageIconInfo);
       
menuItemSave = new JMenuItem("Save", imageIconSave);
       
menuItemOpen = new JMenuItem("Open", imageIconOpen);
       
menuItemNew = new JMenuItem("New", imageIconNew);

       
menuPlik.add(menuItemNew);
       
menuPlik.add(menuItemZamknij);
       
menuPlik.add(menuItemOpen);
       
menuPlik.add(menuItemSave);

       
menuEdycja.add(menuItemKopiuj);
       
menuEdycja.add(menuItemWklej);
       
menuInfo.add(menuItemInfo);

       
menuItemZamknij.addActionListener(this);
       
menuItemKopiuj.addActionListener(this);
       
menuItemWklej.addActionListener(this);
       
menuItemInfo.addActionListener(this);
       
menuItemSave.addActionListener(this);
       
menuItemOpen.addActionListener(this);
       
menuItemNew.addActionListener(this);

       
setJMenuBar(jMenuBar);

       
setContentPane(panelG);
       
setVisible(true);
   
}

   
public static void main(String[] args) {
       
new Notatki();
   
}

   
@Override
   
public void actionPerformed(ActionEvent e) {
        Object o = e.getSource()
;
        if
(o==menuItemZamknij || o==buttonZamknij){
            System.exit(
0);
       
}else if(o==menuItemKopiuj || o==buttonKopiuj){
           
textArea.copy();
       
}else if(o==menuItemWklej || o==buttonWklej){
           
textArea.paste();
       
}else if(o==menuItemInfo || o==buttonInfo){
            JOptionPane.showMessageDialog(Notatki.this
,
                   
"Aplikacja z wykładu nr 9 pokazująca działanie strumieni znakowych" +
                           
"\nautor programu: Jan Kowalski");
       
}else if(o==menuItemOpen || o==buttonOpen){
            openFile()
;
        
}else if(o==menuItemSave || o==buttonSave){
            saveFile()
;
       
}else if(o==menuItemNew || o==buttonNew){
           
textArea.setText("");
       
}
    }

   
private void saveFile() {

        String tekst =
textArea.getText();
        try
{
           
final JFileChooser fc = new JFileChooser();
           
FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT file - (*.txt)", "txt");
           
fc.setFileFilter(filter);

            int
returnVal = fc.showSaveDialog(this);
           
File file;
            if
(returnVal == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile()
;

               
FileWriter fileWriter = new FileWriter(file.toString()+".txt");
               
fileWriter.write(tekst);
                
fileWriter.close();
           
}
        }
catch (IOException e1) {
            e1.printStackTrace()
;
       
}
    }

   
private void openFile() {

       
final JFileChooser fc = new JFileChooser();
       
FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT file - (*.txt)", "txt");
      
fc.setFileFilter(filter);
        int
returnVal = fc.showOpenDialog(this);

        if
(returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile()
;

           
System.out.println(file.toString());
            try
{
                Scanner scanner =
new Scanner(file);
               
String tekst="";
                while
(scanner.hasNextLine()) {
                    tekst+=scanner.nextLine()+
"\n";
               
}
                System.out.println(tekst)
;
               
textArea.setText(tekst);

           
} catch (FileNotFoundException e) {
                e.printStackTrace()
;
           
}
        }
    }

}

 

 

 

Zapisanie tablicy bajtów do pliku. Poniższy przykład zawiera tablicę danych bajtowych tworzących obrazek w formacie gif:

 

import java.io.FileOutputStream;
import java.io.IOException;
 
public class ZapisBajtowDoPliku {
 
    public static void main(String[] args) {
 
        int dane[]={0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x14, 0x00, 0x14, 0x00, 0xa5, 0x29, 0x00, 0x00, 0x00, 0x00, 0x03,
                    0x03, 0x03, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x0b, 0x0b, 0x0b, 0x0d, 0x0d, 0x0d, 0x11, 0x11,
                    0x11, 0x13, 0x13, 0x13, 0x14, 0x14, 0x14, 0x18, 0x18, 0x18, 0x1d, 0x1d, 0x1d, 0x1e, 0x1e, 0x1e,
                    0x22, 0x22, 0x22, 0x24, 0x24, 0x24, 0x26, 0x26, 0x26, 0x29, 0x29, 0x29, 0x47, 0x47, 0x47, 0x4f,
                    0x4f, 0x4f, 0x5a, 0x5a, 0x5a, 0x5e, 0x5e, 0x5e, 0x5f, 0x5f, 0x5f, 0x61, 0x61, 0x61, 0x66, 0x66,
                    0x66, 0x79, 0x79, 0x79, 0x9e, 0x9e, 0x9e, 0xab, 0xab, 0xab, 0xae, 0xae, 0xae, 0xb0, 0xb0, 0xb0,
                    0xb8, 0xb8, 0xb8, 0xc1, 0xc1, 0xc1, 0xd3, 0xd3, 0xd3, 0xda, 0xda, 0xda, 0xe0, 0xe0, 0xe0, 0xe7,
                    0xe7, 0xe7, 0xe9, 0xe9, 0xe9, 0xeb, 0xeb, 0xeb, 0xef, 0xef, 0xef, 0xf1, 0xf1, 0xf1, 0xf5, 0xf5,
                    0xf5, 0xf7, 0xf7, 0xf7, 0xfd, 0xfd, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x21, 0xfe, 0x11, 0x43,
                    0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, 0x4d, 0x50,
                    0x00, 0x21, 0xf9, 0x04, 0x01, 0x0a, 0x00, 0x3f, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00,
                    0x14, 0x00, 0x00, 0x06, 0x7f, 0xc0, 0x94, 0x70, 0x48, 0x2c, 0x1a, 0x8f, 0xc8, 0x22, 0x40, 0x48,
                    0x72, 0xa4, 0x00, 0x80, 0x01, 0x47, 0xb8, 0xa4, 0x0e, 0xab, 0x10, 0xcc, 0x13, 0xda, 0xb0, 0x7a,
                    0x9f, 0x29, 0x0f, 0xc3, 0x4a, 0x09, 0x7c, 0xab, 0xe0, 0xc7, 0xc6, 0x2a, 0xaa, 0xa2, 0xdf, 0x99,
                    0x2e, 0xdb, 0x7d, 0xbd, 0x22, 0x3a, 0xf5, 0x8a, 0x19, 0x7c, 0x26, 0x80, 0xae, 0x5c, 0x67, 0x57,
                    0x16, 0x10, 0x80, 0x02, 0x53, 0x7c, 0x28, 0x6f, 0x27, 0x05, 0x25, 0x5f, 0x54, 0x23, 0x29, 0x21,
                    0x6f, 0x29, 0x12, 0x13, 0x8f, 0x29, 0x01, 0x1a, 0x29, 0x19, 0x7b, 0x60, 0x25, 0x06, 0x28, 0x7c,
                    0x43, 0x07, 0x0d, 0x1f, 0x0c, 0x08, 0x75, 0x29, 0x11, 0x17, 0xa3, 0x42, 0x12, 0x50, 0x00, 0x14,
                    0xaa, 0x23, 0x09, 0xae, 0x29, 0x26, 0x0a, 0x00, 0x0b, 0x27, 0x49, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2,
                    0xc3, 0xc4, 0x42, 0x41, 0x00, 0x3b, 0x3b};
 
        try{
            FileOutputStream plik = new FileOutputStream ("kpu.gif");
           for (int i=0; i<dane.length; i++)
                plik.write(dane[i])
          plik.close();
 
        }catch (IOException e){
            System.out.println("Error - Nie można otworzyć pliku!"+ e.toString());
        }
    }
}

 

Program odczytuje kolejne bajty danych z pliku kpu.gif oraz wyświetla w konsoli:

 

import java.io.*;
 
public class OdczytBajtowZPliku {
 
          public static void main (String a[]){
            try{
                FileInputStream plik = new FileInputStream ("kpu.gif");
                BufferedInputStream bufor = new BufferedInputStream(plik);
                boolean eof =false;
                int count=0;
 
                while (!eof){
                    int input = bufor.read();
                    System.out.print(input+" ");
                    if (input==-1) eof=true;
                    else
                        count++;
                }
 
                plik.close();
                System.out.println("\n\n Odczytanych bajtow: "+count);
            }
            catch (IOException e){
                System.out.println("Error - Nie można otworzyć pliku!"+e.toString());
            }
    }
}

 

 

Przykład aplikacji wykorzystującej strumienie bajtowe do zapisywania i odczytywania danych do/z pliku kpu.pgif:

 

import javax.swing.*;
import
java.awt.*;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.io.*;

public class
EdytorBajtow extends JFrame {
    JTextField
tab[];
    final int
MAX=400;
   
JPanel panel, panelG;
    int
count=0;

   
EdytorBajtow() {
       
super("Edytor bajtowy");
       
setSize(600, 500);
       
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);
       
Image imageIconFrame = new ImageIcon(getClass().getClassLoader().getResource("ikona_logo.png")).getImage();
       
setIconImage(imageIconFrame);
       
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
panelG = new JPanel(new BorderLayout());
       
JToolBar toolBar = new JToolBar();
       
JButton buttonSave = new JButton(new ImageIcon(getClass().getClassLoader().getResource("save.png")));
       
toolBar.add(buttonSave);

       
buttonSave.addActionListener(new ActionListener() {
           
@Override
           
public void actionPerformed(ActionEvent e) {

               
try{
                    FileOutputStream plik =
new FileOutputStream ("kpu.gif");
                    for
(int i=0; i<tab.length; i++)
                       
if(i<count)
                            plik.write(Integer.parseInt(
tab[i].getText()));

                   
plik.close();
                   
System.out.println("Dane zapisane");

               
}catch (IOException ee){
                    System.out.println(
"Error "+ e.toString());
               
}
            }
        })
;

       
JButton buttonOpen = new JButton(new ImageIcon(getClass().getClassLoader().getResource("open.png")));
       
toolBar.add(buttonOpen);
       
buttonOpen.addActionListener(new ActionListener() {
           
@Override
           
public void actionPerformed(ActionEvent e) {
                System.out.println(
"OK");
               
pobierzDaneZPliku();
           
}
        })
;
       
panelG.add(toolBar, BorderLayout.NORTH);
       
setContentPane(panelG);
       
setVisible(true);
   
}

   
private void pobierzDaneZPliku() {
       
panel = new JPanel(new GridLayout(20,20));
       
tab=new JTextField [MAX];

        try
{
            FileInputStream plik =
new FileInputStream ("kpu.gif");
           
BufferedInputStream bufor = new BufferedInputStream(plik);
            boolean
eof =false;
           
count=0;

            while
(!eof && count<MAX){
               
int input = bufor.read();
               
tab[count] = new JTextField(""+input);
               
panel.add(tab[count]);
               
System.out.print(input+" ");

                if
(input==-1) eof=true;
                else
                   
count++;
           
}
            plik.close()
;
           
System.out.println("\n\n Odczytanych bajtow: "+count);
           
panelG.add(panel, BorderLayout.CENTER);
           
panelG.updateUI();

       
}
       
catch (IOException e){
            System.out.println(
"Error - Nie można otworzyć pliku!"+e.toString());
       
}
    }

   
public static void main(String[] args) {
       
new EdytorBajtow();
   
}
}

 

 

 

4.      Zadania

 

Zadanie 1

Napisz program szyfrujący pliki. Wykorzystaj strumienie bajtowe. Szyfrowanie powinno polegać na modyfikacji bajtów danych pliku.

 

Zadanie 2

Do programu pierwszego dodaj możliwość zapisania wybranych ustawień programu do pliku tekstowego.