|
|
Регистрация Восстановить пароль |
Регистрация | Задать вопрос |
Заплачу за решение |
Новые сообщения |
Сообщения за день |
Расширенный поиск |
Правила |
Всё прочитано |
|
Опции темы | Поиск в этой теме |
08.04.2016, 21:03 | #1 |
Новичок
Джуниор
Регистрация: 08.04.2016
Сообщений: 1
|
Произвольный доступ к файлу через JFileChooser
Возникло непонимание темы = произвольный доступ к файлу. Необзодимо сохранить данные и открыть сохраненные данные.
В основном классе у меня присутствуют следующие действия: Использую JFileChooser чтобы открыть файл: Код HTML:
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"); } } }); [/code] Использую JFileChooser чтобы сохранить файл: [code=java] 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()); } } MyRandomFile написан следующим образом: Код HTML:
public class MyRandomFile { private static final int NUMBER_RECORDS = 100; private RandomAccessFile output; private RandomAccessFile input; public void createFile() { RandomAccessFile file = null; try // open file for reading and writing { file = new RandomAccessFile( "clients.dat", "rw" ); RandomAccessEmployeeRecord blankRecord = new RandomAccessEmployeeRecord(); 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); 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: Вопрос заключается в том, как вызвать методы с этих двух классов в JFileChooser и нужно ли использовать каки-либо параметры и если да(что мне кажется более вероятным), то какие. На самом деле нет полного понимания данной темы, поэтому я очень запуталась и извините заранее за такой вопрос. |
Похожие темы | ||||
Тема | Автор | Раздел | Ответов | Последнее сообщение |
Не могу получить доступ к файлу через PascalABCNET | Neitrat | Помощь студентам | 22 | 07.02.2016 16:26 |
Не могу получить доступ к файлу через PascalABCNET | Neitrat | Паскаль, Turbo Pascal, PascalABC.NET | 0 | 06.02.2016 17:27 |
Работа с файлами. Произвольный доступ. с++ | ahab | Помощь студентам | 1 | 17.03.2010 00:51 |
произвольный доступ к файлам | StudentPolitech | Общие вопросы C/C++ | 7 | 06.06.2009 14:28 |