Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Произвольный доступ к файлу через JFileChooser 
:(
    Опции темы
Golt
Дата 8.4.2016, 20:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 6.12.2015

Репутация: нет
Всего: нет



Возникло непонимание темы = произвольный доступ к файлу. Необзодимо сохранить данные и открыть сохраненные данные.

В основном классе у меня присутствуют следующие действия:

Использую JFileChooser чтобы открыть файл:

Код

openItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fileChooser = new JFileChooser(".");

    fileChooser.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Action");


      }
    });


    int status = fileChooser.showOpenDialog(null);


    if (status == JFileChooser.APPROVE_OPTION) {
      File selectedFile = fileChooser.getSelectedFile();
      System.out.println(selectedFile.getParent());
      System.out.println(selectedFile.getName());
    } else if (status == JFileChooser.CANCEL_OPTION) {
      System.out.println("calceled");

    }

  }
}); 

Использую JFileChooser чтобы сохранить файл:
Код

saveItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    showSaveFileDialog();

                }
            });

    private void showSaveFileDialog() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Specify a file to save");

        int userSelection = fileChooser.showSaveDialog(this);
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();
            //fileChooser.getSelectedFile().openFileWriting();
            RandomAccessEmployeeRecord record = new RandomAccessEmployeeRecord();
            //record.openFileWriting();

            System.out.println("Save as file: " + fileToSave.getAbsolutePath());
        }
    }



Далее имеются еще два класса под названиями RandomAccessEmployeeRecord и MyRandomFile.

MyRandomFile написан следующим образом:

Код


public class MyRandomFile
{    
   private static final int NUMBER_RECORDS = 100;
   private RandomAccessFile output;
   private RandomAccessFile input;


   // enable user to select file to open
   public void createFile()
   {
      RandomAccessFile file = null;

      try // open file for reading and writing
      {           
         file = new RandomAccessFile( "clients.dat", "rw" );

         RandomAccessEmployeeRecord blankRecord = 
            new RandomAccessEmployeeRecord();

         // write 100 blank records
         for ( int count = 0; count < NUMBER_RECORDS; count++ )
            blankRecord.write( file );

         // display message that file was created
         System.out.println( "Created file employees.dat." );

         //System.exit( 0 ); // terminate program
      } // end try
      catch ( IOException ioException )
      {
         System.err.println( "Error processing file." );
         System.exit( 1 );
      } // end catch
      finally
      {
         try
         {
            if ( file != null )
               file.close(); // close file
               System.out.println("Bye");
         } // end try
         catch ( IOException ioException )
         {
            System.err.println( "Error closing file." );
            System.exit( 1 );
         } // end catch
      } // end finally
   } // end method createFile



   // enable user to choose file to open
   public void openFileReading()
   {
          try // open file
          {
             input = new RandomAccessFile( "employees.dat", "r" );
          } // end try
          catch ( IOException ioException )
          {
             System.err.println( "File does not exist." );
          } // end catch
       } // end method openFile

   public void openFileWriting()
   {
          try // open file
          {
             output = new RandomAccessFile( "employees.dat", "rw" );
          } // end try
          catch ( IOException ioException )
          {
             System.err.println( "File does not exist." );
          } // end catch
   }   

   // close file and terminate application
   public void closeFile() 
   {
      try // close file and exit
      {
         if ( output != null )
               output.close();

             if ( input != null )
                 input.close();       
      } // end try
      catch ( IOException ioException )
      {
         System.err.println( "File does not exist." );
      } // end catch
   } // end method closeFile

   // add records to file
   public void addRecords()
   {
      // object to be written to file
      RandomAccessEmployeeRecord record = new RandomAccessEmployeeRecord();

        int id;
        String pps;
        String name;
        String surname;
        boolean gender;
        String dep;
        int salary;
        boolean fulltime;

      Scanner input = new Scanner( System.in );


      while ( input.hasNext() ) // loop until end-of-file indicator
      {
         try // output values to file
         {

            id = input.nextInt();
            pps = input.next();
            name = input.next();
            surname = input.next();
            gender = input.nextBoolean();
            dep = input.next();
            salary = input.nextInt();
            fulltime = input.nextBoolean();


            if (pps.length()==7 )
            {
                 record.setPps(pps);
                 record.setName(name);
                 record.setSurname(surname);
                 record.setGender(gender);
                 record.setDep(dep);
                 record.setSalary (salary);
                 record.setFulltime (fulltime);

         //      output.seek( ( pps. - 1 ) * // position to proper
    //           RandomAccessEmployeeRecord.SIZE ); // location for file
               record.write( output );
            } // end if
            else
               System.out.println( "PPs must be with 7 characters or numbers." );
         } // end try
         catch ( IOException ioException )
         {
            System.err.println( "Error writing to file." );
            return;
         } // end catch
         catch ( NoSuchElementException elementException )
         {
            System.err.println( "Invalid input. Please try again." );
            input.nextLine(); // discard input so user can try again
         } // end catch

      //   System.out.printf( "%s %s\n%s", "Enter account number (1-100),",
        //    "first name, last name and balance.", "? " );
      } // end while
   } // end method addRecords

   // read and display records
   public void readRecords()
   {

      RandomAccessEmployeeRecord record = new RandomAccessEmployeeRecord();
   //   record.seek(location);

      System.out.printf( "%-10s%-15s%-15s%10s\n", "pps", "name", "surname", "gender", "dep", "salary", "fulltime" );

      try // read a record and display
      {
         while ( true )
         {
            do
            {
               record.read( input );
            } while ( record.getId() == 0 );

            // display record contents
            System.out.printf( "%-10d%-12s%-12s%10.2f\n",
               record.getPps(), record.getName(),
               record.getSurname(), record.getGender(),
               record.getDep(), record.getSalary(), record.getFullTime());

         } // end while
      } // end try
      catch ( EOFException eofException ) // close file
      {
         return; // end of file was reached
      } // end catch
      catch ( IOException ioException )
      {
         System.err.println( "Error reading file." );
         System.exit( 1 );
      } // end catch
   } // end method readRecords
}



RandomAccessAccountRecord:


Код

public class RandomAccessEmployeeRecord extends Employee
{  
    public RandomAccessEmployeeRecord(String pps, String name, String surname,
            boolean gender, String dep, int salary, boolean fulltime) {
        super(pps, name, surname, gender, dep, salary, fulltime);
        // TODO Auto-generated constructor stub
    }

    public static final int SIZE = 1200;

   // no-argument constructor calls other constructor with default values
   public RandomAccessEmployeeRecord()
   {
      this( "", "", "", false, "", 0, false );
   } // end no-argument RandomAccessAccountRecord constructor


   // read a record from specified RandomAccessFile
   public void read( RandomAccessFile file ) throws IOException
   {
      setPps( readName( file ) );
      setName( readName( file ) );
      setSurname( readName( file ) );
      setGender( file.readBoolean() );
      setDep( readName( file ) );
      setSalary ( file.readInt() );
      setFulltime ( file.readBoolean() );

   } // end method read

   // ensure that name is proper length
   private String readName( RandomAccessFile file ) throws IOException
   {
      char name[] = new char[ 15 ], temp;

      for ( int count = 0; count < name.length; count++ )
      {
         temp = file.readChar();
         name[ count ] = temp;
      } // end for     

      return new String( name ).replace( '\0', ' ' );
   } // end method readName

   // write a record to specified RandomAccessFile
   public void write( RandomAccessFile file ) throws IOException
   {

       writeName( file, getPps());
       writeName( file, getName());
       writeName( file, getSurname());
       writeName( file, getGender());
       writeName( file, getDep());
       file.writeInt( getSalary() );
       writeName( file, getFullTime());


   } // end method write

   // write a name to file; maximum of 15 characters
   private void writeName( RandomAccessFile file, String name )
      throws IOException
   {
      StringBuffer buffer = null;

      if ( name != null ) 
         buffer = new StringBuffer( name );
      else 
         buffer = new StringBuffer( 15 );

      buffer.setLength( 15 );
      file.writeChars( buffer.toString() );
   } // end method writeName
} // end class RandomAccessAccountRecord


Вопрос заключается в том, как вызвать методы с этих двух классов в JFileChooser и нужно ли использовать каки-либо параметры и если да(что мне кажется более вероятным), то какие.

На самом деле нет полного понимания данной темы, поэтому я очень запуталась и извините заранее за такой вопрос.
PM MAIL   Вверх
Mirkes
Дата 10.5.2016, 18:42 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 586
Регистрация: 18.8.2011
Где: Красноярск

Репутация: 7
Всего: 17



У Вас мешанина в терминологии. JFileChooser служит для выбора файла, а точнее имени файла. Он не создает и не открывает файлы.
В классе MyRandomFile создайте метод createFile(File myFile):

      RandomAccessFile file = null;
       try // open file for reading and writing
      {           
         file = new RandomAccessFile( myFile, "rw" ); //НЕ стандартное а
                                                      //выбранное имя

    // Чего-то пишем.

      } // end try
      catch ( IOException ioException )
      {
         System.err.println( "Error processing file." );
         System.exit( 1 );
      } // end catch


При выборе файла для сохранения используйте
  File fileToSave = fileChooser.getSelectedFile(); //Есть файл для записи, но он
                                                   //не открыт.
  MyRandomFile mrFile = new MyRandomFile(); //Это объект, который даст доступ ко
                                            //все еще не открытому файлу
  MyRandomFile.createFile(fileToSave ); //А вот теперь создаем и открываем файл.
            

Этот ответ добавлен с нового Винграда - http://vingrad.com
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.1350 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.