Sei sulla pagina 1di 19

A text file can be read line-by-line with a BufferedReader.

To sort these lines, we can read them into a List and run a Collections.sort() on the List. The AlphabeticallySortLinesOfTextInFile class demonstrates this. It reads in a t ext file line-by-line and adds each line to an ArrayList. When this is done, it sorts the list with Collections.sort(). To display the results, it outputs all t he lines to an output file using a PrintWriter and FileWriter. AlphabeticallySortLinesOfTextInFile.java package test; import import import import import import import java.io.BufferedReader; java.io.FileReader; java.io.FileWriter; java.io.PrintWriter; java.util.ArrayList; java.util.Collections; java.util.List;

public class AlphabeticallySortLinesOfTextInFile { public static void main(String[] args) throws Exception { String inputFile = "input.txt"; String outputFile = "output.txt"; FileReader fileReader = new FileReader(inputFile); BufferedReader bufferedReader = new BufferedReader(fileReader); String inputLine; List<String> lineList = new ArrayList<String>(); while ((inputLine = bufferedReader.readLine()) != null) { lineList.add(inputLine); } fileReader.close(); Collections.sort(lineList); FileWriter fileWriter = new FileWriter(outputFile); PrintWriter out = new PrintWriter(fileWriter); for (String outputLine : lineList) { out.println(outputLine); } out.flush(); out.close(); fileWriter.close(); } } The input file is shown here. input.txt this is a file that we are using to test If we execute AlphabeticallySortLinesOfTextInFile, it generates the output.txt f ile shown below. output.txt

import java.io.*; import java.util.*; public class FilebubbleSortExample{ public static void main(String a[])throws Exception{ ArrayList<Integer> list=new ArrayList<Integer>(); BufferedReader br=new BufferedReader(new FileReader("num.txt")); BufferedWriter bw=new BufferedWriter(new FileWriter("new.txt",true)); String st=""; while((st=br.readLine())!=null){ list.add(new Integer(Integer.parseInt(st))); } int i; int array[] = toIntArray(list); System.out.println("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print(array[i]+" "); System.out.println(); bubble_srt(array, array.length); System.out.print("Values after the sort:\n"); for(i = 0; i <array.length; i++){ System.out.print(array[i]+" "); bw.write(Integer.toString(array[i])); bw.newLine(); } bw.close(); System.out.println(); } public static void bubble_srt( int a[], int n ){ int i, j,t=0; for(i = 0; i < n; i++){ for(j = 1; j < (n-i); j++){ if(a[j-1] > a[j]){ t = a[j-1]; a[j-1]=a[j]; a[j]=t; } } } } static int[] toIntArray(List<Integer> integerList) { int[] intArray = new int[integerList.size()]; for (int i = 0; i < integerList.size(); i++) { intArray[i] = integerList.get(i); } return intArray; } }

package test; import import import import java.io.File; java.io.IOException; java.util.Collections; java.util.List;

import org.apache.commons.io.FileUtils; public class ReadListOfLinesFromFileAndAlphabetize { public static void main(String[] args) { try { File file = new File("test.txt"); List<String> lines = FileUtils.readLines(file); Collections.sort(lines); for (String line : lines) { System.out.println("line:" + line); } } catch (IOException e) { e.printStackTrace(); } } } The test.txt file is shown here: test.txt this is a test of commons io Executing ReadListOfLinesFromFileAndAlphabetize with test.txt generates the foll owing console output: line:a test line:of commons io line:this is

package test; import import import import java.io.BufferedReader; java.io.File; java.io.FileReader; java.io.IOException;

public class ReadStringFromFileLineByLine {

public static void main(String[] args) { try { File file = new File("test.txt"); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileR eader); StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); stringBuffer.append("\n"); } fileReader.close(); System.out.println("Contents of file:"); System.out.println(stringBuffer.toString()); } catch (IOException e) { e.printStackTrace(); } } } In this class, the test.txt file is read via a FileReader, which in turn is fed to a BufferedReader. The BufferedReader is read line-by-line, and each line is a ppended to a StringBuffer, followed by a linefeed. The contents of the StringBuf fer are then output to the console. The test.txt file is shown below. test.txt this is a test file

package test; import import import import import import import java.io.BufferedReader; java.io.FileReader; java.io.FileWriter; java.io.PrintWriter; java.util.ArrayList; java.util.Collections; java.util.List;

public class AlphabeticallySortLinesOfTextInFile { public static void main(String[] args) throws Exception { String inputFile = "input.txt"; String outputFile = "output.txt"; FileReader fileReader = new FileReader(inputFile); BufferedReader bufferedReader = new BufferedReader(fileReader); String inputLine; List<String> lineList = new ArrayList<String>(); while ((inputLine = bufferedReader.readLine()) != null) { lineList.add(inputLine); } fileReader.close();

Collections.sort(lineList); FileWriter fileWriter = new FileWriter(outputFile); PrintWriter out = new PrintWriter(fileWriter); for (String outputLine : lineList) { out.println(outputLine); } out.flush(); out.close(); fileWriter.close(); } } The input file is shown here. input.txt this is a file that we are using to test If we execute AlphabeticallySortLinesOfTextInFile, it generates the output.txt f ile shown below. output.txt are using to test file that we this is a

// Source File Name: TextIO.java import import import import java.awt.*; java.awt.event.*; java.io.*; javax.swing.*;

public class TextIO extends JFrame implements ActionListener { public TextIO() { super("TextIO Demo"); display = new JTextArea(); read = new JButton("Read From File"); write = new JButton("Write to File"); sort = new JButton("Sort File"); nameField = new JTextField(20); prompt = new JLabel("Filename:", 4); commands = new JPanel(); read.addActionListener(this); write.addActionListener(this); sort.addActionListener(this); commands.setLayout(new GridLayout(2, 2, 1, 1)); commands.add(prompt); commands.add(nameField); commands.add(read);

commands.add(write); commands.add(sort); display.setLineWrap(true); getContentPane().setLayout(new BorderLayout()); getContentPane().add("North", commands); getContentPane().add(new JScrollPane(display)); getContentPane().add("Center", display); } private void readTextFile(JTextArea jtextarea, String s) { try { BufferedReader bufferedreader = new BufferedReader(new FileReader(s)); for(String s1 = bufferedreader.readLine(); s1 != null; s1 = bufferedreader.readL ine()) jtextarea.append(s1 + "\n"); bufferedreader.close(); } catch(FileNotFoundException filenotfoundexception) { jtextarea.setText("IOERROR: File NOT Found: " + s + "\n"); filenotfoundexception.printStackTrace(); } catch(IOException ioexception) { jtextarea.setText("IOERROR: " + ioexception.getMessage() + "\n"); ioexception.printStackTrace(); } } // bubbleSort() sorts the values in arr into ascending order // Pre: arr is equal null. private void bubbleSort(int arr[]) { if (arr == null) throw new NullPointerException("ERROR:Array cannot be null"); int temp; //Temporary variable for (int pass = 1; pass < arr.length; pass++) // For each pass for (int pair = 1; pair < arr.length; pair++) // For each pair if (arr[pair-1] > arr[pair]) { // Compare temp = arr[pair-1]; // and swap arr[pair-1] = arr[pair]; arr[pair] = temp; }//if } // bubbleSort() // print() prints the values in an array public void print(int arr[]) { for (int k = 0; k < arr.length; k++) // For each integer System.out.print( arr[k] + " \t "); // Print it System.out.println(); } // print() private void writeTextFile(JTextArea jtextarea, String s) { try

{ FileWriter filewriter = new FileWriter(s); filewriter.write(jtextarea.getText()); filewriter.close(); } catch(IOException ioexception) { jtextarea.setText("IOERROR: " + ioexception.getMessage() + "\n"); ioexception.printStackTrace(); } } public void actionPerformed(ActionEvent actionevent) { String s = nameField.getText(); if(actionevent.getSource() == read) { display.setText(""); readTextFile(display, s); } else { writeTextFile(display, s); } } public static void main(String args[]) { TextIO textio = new TextIO(); textio.setSize(400, 200); textio.setVisible(true); textio.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowevent) { System.exit(0); } }); } private private private private private private private } JTextArea display; JButton read; JButton write; JButton sort; JTextField nameField; JLabel prompt; JPanel commands;

Reply Share By Email Share By Email Report Re: Read in text file, sort it, then output to a file, Posted by nightsurfer on 17 Dec 2001 at 5:41 PM here's a sorting method for a fully populated array of integers: public static int[] bubbleSort(int[] ar) { int stop = ar.length; int small; int[] tmp = new int[ar.length];

for (int i = 0; i < ar.length; i++) { small = ar[0]; for (int j = 0; j < stop; j++) { if (small > ar[j]) small = ar[j]; ar[j] = ar[stop - 1]; ar[stop - 1] = small; } tmp[i] = small; stop--; } return tmp; } I have not tested this, so it may not sort from start to finish, but if you play around with the ranges for the two loops it will work. The general idea is OK, and the complexity is O(N^2) which isn't so good, but it's not too bad either. Hope this helps. Cheers. Later in life you will be more disappointed by the things you haven't done than by those you have. So cast off the bowlines and sail away into the seas of oppor tunity. Reply Share By Email Share By Email

How to use Java to write in a ".txt" file and read that ".txt" file. I am writing a program that has a few requirements. Here is what it looks like the picture that I attached. The first button is used to add (append) a record to a text file containing MP3 records. When an MP3 is added to the file, all text fields should be cleared and the new record entered should be displayed by itself in the text area: If a fie ld is missing inform the user. Add AT LEAST six MP3 records. The data must be wr itten to the text file using a : as a separator: artist name:song name:album name: tract length(in seconds such as 435) The second button displays all MP3 records from the file sorted by artist name. Store the MP3s in an ArrayList. The MP3 records should be displayed in sorted or der by artist name using a sort method that is modified to work with MP3 objects . You should use compareTo to compare the MP3 artist names for sorting. You shou ld call the toString method to display the MP3 records. artist name, song name, album name, 7:15 The third button will find and display a record if the user enters the song name . If the song cannot be found then inform the user. The delete button will delete a record from the file based on the song name. Rea d the file data into an ArrayList. If the record to delete is found, do not plac e it in the ArrayList. After the records have been read in, if the delete record

was found then close the file and reopen it in write mode. Use a Yes/No dialog box to confirm the delete. Write the records back into the file. If the record w as not found, inform the user, close the file, and discard the ArrayList. Use must use exception handling for the file I/O and for any other possible exce ptions. You should NOT leave the data file open.Open it ONLY when you need to access the data and close it immediately when you are finished. Here is the MP3 class public class MP3 { private String artist; private String song; private String album; private int trackLength; public MP3(String artistName, String songName, String albumName, int trackLeng) { setArtist(artistName); setSong(songName); setAlbum(albumName); setTrackLength(trackLeng); } public void setArtist(String artistName) { artist = artistName; } public String getArtist() { return artist; } public void setSong(String songName) { song = songName; } public String getSong() { return song; } public void setAlbum(String albumName) { album = albumName; } public String getAlbum() { return album; } public void setTrackLength(int trackLeng) { trackLength = (trackLeng > 0) ? trackLeng : 5 ; } public int getTrackLength() { return trackLength; } public String toString() { return String.format("%s, %s, %s, %d : %d", getArtist(), getSong(), getAlbum(), getTrackLength() / 60, getTrackLength() % 60); } } here is the partially done MP3Manager class, I need help on sorting this by arti st name, and correctly fuctioned on writing in the "Record.txt" file and reading that file. In addition, I also need help to use dialog box to confirm the delet ing information

import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; public class MP3Manager extends JFrame{ private JButton addMP3Button, displayMP3sButton, findMP3Button, deleteMP3But ton; private JLabel artistLabel, songLabel, albumLabel, trackLengthLabel; private JTextField artistField, songField, albumField, trackLengthField; private JPanel fieldsPanel; private JTextArea textArea; private ArrayList <MP3> mp3List; public MP3Manager(){ super("MP3 Manager"); fieldsPanel = new JPanel(new GridLayout(6, 2, 5, 5)); mp3List = new ArrayList<MP3>(); artistLabel = new JLabel("Artist Name ", JLabel.RIGHT); artistField = new JTextField(); artistField.setHorizontalAlignment(JTextField.CENTER); fieldsPanel.add(artistLabel); fieldsPanel.add(artistField); songLabel = new JLabel("Song Title ", JLabel.RIGHT); songField = new JTextField(); songField.setHorizontalAlignment(JTextField.CENTER); fieldsPanel.add(songLabel); fieldsPanel.add(songField); albumLabel = new JLabel("Album Name ", JLabel.RIGHT); albumField = new JTextField(); albumField.setHorizontalAlignment(JTextField.CENTER); fieldsPanel.add(albumLabel); fieldsPanel.add(albumField); trackLengthLabel = new JLabel("Track Length (in seconds) ", JLabel.RIGHT); trackLengthField = new JTextField("", 16); trackLengthField.setHorizontalAlignment(JTextField.CENTER); fieldsPanel.add(trackLengthLabel); fieldsPanel.add(trackLengthField); addMP3Button = new JButton(" Add MP3 "); displayMP3sButton = new JButton(" Display MP3s "); findMP3Button = new JButton(" Find MP3 "); deleteMP3Button = new JButton(" Delete MP3 "); fieldsPanel.add(addMP3Button); fieldsPanel.add(displayMP3sButton); fieldsPanel.add(findMP3Button); fieldsPanel.add(deleteMP3Button); textArea = new JTextArea(); textArea.setEditable(false); add(fieldsPanel, BorderLayout.NORTH); add(textArea, BorderLayout.CENTER); ButtonHandler handler = new ButtonHandler(); addMP3Button.addActionListener(handler); displayMP3sButton.addActionListener(handler); findMP3Button.addActionListener(handler); deleteMP3Button.addActionListener(handler); } private class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ int length = 0; String artist = artistField.getText(); String album = albumField.getText();

String song = songField.getText(); if(event.getSource() == addMP3Button){ try{ length = Integer.parseInt(trackLengthField.getText()); }catch(Exception e){ textArea.setText("Track Length must be integer."); return; } if(length <= 0){ textArea.setText("Track Length must be positive."); return; } if(artist.trim().length() == 0){ textArea.setText("Please fill out complete infotmation. \nArtist Field must be not empty."); return; } if(album.trim().length() == 0){ textArea.setText("Please fill out complete infotmation. \nAblum Field must b e not empty."); return; } if(song.trim().length() == 0){ textArea.setText("Please fill out complete infotmation. \nSong Field must be not empty."); return; } MP3 songs = new MP3(artist, song, album, length); mp3List.add(songs); textArea.setText("Song added successfully"); artistField.setText(""); songField.setText(""); albumField.setText(""); trackLengthField.setText(""); try{ File file = new File("Record.txt"); PrintWriter pw = new PrintWriter(new FileWriter(file, true)); for(MP3 mp3 : mp3List) pw.print(mp3.getArtist() + ":" + mp3.getSong() + ":" + mp3.getAlbum() + ":" + mp3.getTrackLength() + "\n"); pw.close(); }catch(IOException e){ System.out.println("Error creating file" + e); } } if(event.getSource() == displayMP3sButton){ File file = new File("Record.txt"); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(file)); String text = null; while((text = reader.readLine()) != null){ contents.append(text).append(System.getProperty("line.separator")); } }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }finally{

try{ if(reader != null){ reader.close(); } }catch(IOException e){ e.printStackTrace(); } } textArea.setText(""); textArea.append(contents.toString() + "\n"); } if(event.getSource() == findMP3Button){ if(song.equals("")) textArea.setText("Please enter the song name"); else{ boolean found = false; for(MP3 songs : mp3List){ if(songs.getSong().equalsIgnoreCase(song)){ textArea.setText(songs.toString() + "\n"); found = true; break; } } if(!found) textArea.setText("Record cannot be found"); } } if(event.getSource() == deleteMP3Button){ if(song.equals("")) textArea.setText("Please enter the song name"); else{ boolean delete = false; for(MP3 songs : mp3List){ if(songs.getSong().equalsIgnoreCase(song)){ mp3List.remove(songs); textArea.setText(songs.toString() + "\n"); delete = true; break; } } if(!delete) textArea.setText("Record cannot be found"); } } } } } And here is the MP3ManagerTest class import javax.swing.*; import java.awt.*; public class MP3ManagerTest{ public static void main(String[] args) { MP3Manager manager = new MP3Manager(); manager.setSize(400, 500); manager.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); manager.setVisible(true); } }

I am truly appreciated any contribution, If anyone could offer all the help that I need. Thanks in advance. Attachments 1.png 120.93KB 3 Contributors 6 Replies 11 Hours Discussion Span 1 Year Ago Last Updated 7 Views Related Article: Read, Edit and Write to File is a Java code snippet by DavidKro ukamp that has 13 replies, was last updated 1 year ago and has been tagged with the keywords: edit, file, input, java, read, write. Danielhuo Light Poster 27 posts since Nov 2011 Ads by Google Eclipse EJB IDE Visual designer, Roundtrip Engine. Direct edit, Export as XMI & Morewww.myeclips eide.com 1 Year Ago 0 Do you have any specific questions or problems? If so please ask them. If you are getting errors, please copy and paste the full text of the messages h ere. NormR1 Posting Sage Team Colleague 7,742 posts since Jun 2010 1 Year Ago 0 Look up BufferedReader and BufferedWriter. hfx642 Posting Pro 515 posts since Nov 2009 1 Year Ago 0 Do you have any specific questions or problems? If so please ask them. If you are getting errors, please copy and paste the full text of the messag es here. I high light the question. You should be able to see it if you read carefully. It is I need help on sorting this by artist name, and correctly fuctioned on wri ting in the "Record.txt" file and reading that file. In addition, I also need he lp to use dialog box to confirm the deleting information Danielhuo Light Poster 27 posts since Nov 2011 1 Year Ago

0 I high light the question. You should be able to see it if you read carefull y. There were 6 red sections in your post. After I read three of them I saw that th ey were the statement of your assignment so I stopped reading the red sections a nd looked at the end of the post for your questions. There were no questions the re so I asked. Work on one problem at a time Where are the artist names? If they are in a collection, the Collection class ha s sort methods that should be helpful. NormR1 Posting Sage Team Colleague 7,742 posts since Jun 2010 1 Year Ago 0 The artist name is in ArrayList, which contains MP3 objects. The thing is I cann ot use any built in sort method, I have to write simple sort method. Danielhuo Light Poster 27 posts since Nov 2011 1 Year Ago 0 OK, if you need to write a simple sort. I'd suggest that you write a small, simp le program that loads an ArrayList with some objects and then calls a method to sort them. Write the method and test it. Print the arraylist before the sort and after the sort to see if it worked. When you get the method to work, you can copy it into your larger program and te st it there. NormR1 Posting Sage Team Colleague 7,742 posts since Jun 2010 This article has been dead for over three months: Start a new discussion instead Post: Markdown Syntax: Formatting Help Bold Italic Code Inline Code Link Quote Heading Sub-Heading # List List Undo Red o

You Software Development > Java 0 inShare Java RSS Feed View similar articles that have also been tagged: arraylist-sorting box dialog f ilewriter java textfile algorithm android applet application array arraylist arrays awt beginner binary box button c c# c++ calculator card check checkbox class client code coding comb o combobox comparator compiler data database development dialog eclipse error fi le for game gui help homework html image inheritance input jar java javascript j dbc jframe jsp linked list loop map math message method methods mysql name netbe ans news node null object of oracle php problem program programming project pyth on random read recursion recursive regex run scanner script search security serv

er services servlet software sql string swing table text textbox textfile thread time timer tree validation web xml 2013 DaniWeb LLC Page rendered in 0.5276 seconds using 2.34MB Recently Updated Articles Join the DaniWeb Communit

/* Display a text file. To use this program, specify the name of the file that you want to see. For example, to see a file called TEST.TXT, use the following command line. java ShowFile TEST.TXT */ import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("File Not Found"); return; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: ShowFile File"); return; } // read characters until EOF is encountered do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); fin.close(); } } To write to a file, you will use the write( ) method defined by FileOutputStream . Its simplest form is shown here: void write(int byteval) throws IOException This method writes the byte specified by byteval to the file. Although byteval i s declared as an integer, only the low-order eight bits are written to the file. If an error occurs during writing, an IOException is thrown. The next example u ses write( ) to copy a text file: /* Copy a text file. To use this program, specify the name of the source file and the destination

file. For example, to copy a file called FIRST.TXT to a file called SECOND.TXT, us e the following command line. java CopyFile FIRST.TXT SECOND.TXT */ import java.io.*; class CopyFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; FileOutputStream fout; try { // open input file try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("Input File Not Found"); return; } // open output file try { fout = new FileOutputStream(args[1]); } catch(FileNotFoundException e) { System.out.println("Error Opening Output File"); return; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: CopyFile From To"); return; } // Copy File try { do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); } catch(IOException e) { System.out.println("File Error"); } fin.close(); fout.close(); } }

try { scanner = new Scanner(file); //put the database into an array and //make sure each String array is 13 in length while (scanner.hasNext()) { line = scanner.nextLine(); word = line.split(","); if (word.length < 13) { String[] word2 = {"","","","","","","","","","","","",""}; for (int i = 0; i < word.length; i++) { word2[i] = word[i]; } dataBaseArray.add(word2); } else { dataBaseArray.add(word); } } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "File cannot be found.", "error find ing file", JOptionPane.ERROR_MESSAGE); } //splitting the database into vacant numbers/dead lines/vacant cubicles for (int i = 0; i < dataBaseArray.size(); i++) { if (dataBaseArray.get(i)[8].equals("VACANT")) { vacantNums.add(dataBaseArray.get(i)); } else if (dataBaseArray.get(i)[4].equals("DEAD")) { deadLines.add(dataBaseArray.get(i)); } else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7] .equals("")) { vacantCubs.add(dataBaseArray.get(i)); } else if (dataBaseArray.get(i)[7].equals("")) { people.add(dataBaseArray.get(i)); } else { people.add(dataBaseArray.get(i)); } } //resetting the DB Array to put the values back in it dataBaseArray = new ArrayList<>(); //Ordering the arrays i want them to appear in the list //orering the people to appear in alphabetical order Collections.sort(people, new Comparator<String[]>() { @Override public int compare(String[] strings, String[] otherStrings) { return strings[7].compareTo(otherStrings[7]); } }); //put the people in the DB Array for (int i = 0; i < people.size(); i++) { dataBaseArray.add(people.get(i)); }

//put the vacant numbers in the AB Array for (int i = 0; i < vacantNums.size(); i++) { dataBaseArray.add(vacantNums.get(i)); } //put the vacant cubicles in the AB Array for (int i = 0; i < vacantCubs.size(); i++) { dataBaseArray.add(vacantCubs.get(i)); } //put the dead lines in the AB Array for (int i = 0; i < deadLines.size(); i++) { dataBaseArray.add(deadLines.get(i)); } list = new String[dataBaseArray.size()]; //add the DB Array to the list for (int i = 0; i < list.length; i++) { if (dataBaseArray.get(i)[8].equals("VACANT")) { list[i] = "VACANT"; } else if (dataBaseArray.get(i)[4].equals("DEAD")) { list[i] = "DEAD"; } else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7] .equals("")) { list[i] = "Vacant Cubicle"; } else if (dataBaseArray.get(i)[7].equals("")) { list[i] = dataBaseArray.get(i)[6]; } else { list[i] = dataBaseArray.get(i)[7] + ", " + dataBaseArray.get(i)[6]; } } //populate the list lstAdvance.setListData(list);

try { saveFile = new FileWriter("Save Location"); String newLine = System.getProperty("line.separator"); for (int i = 0; i < dataBaseArray.size(); i++) { for (int j = 0; j < dataBaseArray.get(i).length; j++) { saveFile.append(dataBaseArray.get(i)[j] + ","); } saveFile.append(newLine);

} } catch (IOException e) { JOptionPane.showMessageDialog(this,"error", "error", JOptionPane.ERROR_M ESSAGE); }

import java.io.*; import java.util.*; public class Sort { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader("fileToRead")) ; Map<String, String> map=new TreeMap<String, String>(); String line=""; while((line=reader.readLine())!=null){ map.put(getField(line),line); } reader.close(); FileWriter writer = new FileWriter("fileToWrite"); for(String val : map.values()){ writer.write(val); writer.write('\n'); } writer.close(); } private static String getField(String line) { return line.split(" ")[0];//extract value you want to sort on } }

Potrebbero piacerti anche