How to sort a file

How to sort a file, simple unrefractored example
import java.io.*;
import java.util.*;
public
class Sort
   * Sorts a file that contains data per line using a TreeMap
   * @param args There must be at least one argument, and only the first
   * argument will be interpreted
  public
  static
  void main(String[] args)
  throws Exception
    TreeSet set; // used to sort the data
    BufferedReader buffer; // reads from File with name of args[0]
    PrintWriter writer; // writes to File with the name of args[0].sorted
    String line; // buffer for line read
    set = new TreeSet();
    buffer = new BufferedReader(new InputStreamReader(new FileInputStream(args[0])));
    while ((line=buffer.readLine())!=null) set.add(line.trim());
    buffer.close();
    writer = new PrintWriter(new PrintStream(new FileOutputStream(args[0]+".sorted")));
    for (Iterator i = set.iterator(); i.hasNext(); writer.println(i.next()));
    writer.close();

and here is the clean version as a handy static utility method:
      * Sort lines in a text file in alphabetical order.
      * @param sourceFile File to sort.
      * @param destinationFile File to write sorted content to.
      * @throws IOException If error occured.
     public static void sortFile(File sourceFile, File destinationFile) throws IOException {
        if (sourceFile != null) {
            BufferedReader br = null;
            PrintWriter pw = null;
            TreeSet treeSet = new TreeSet(); //used to sort the data
            try {
                String line = null;
                //read source file into treeSet:
                br = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile)));
                while ((line = br.readLine())!=null) {
                    treeSet.add(line.trim());
                //write content of treeSet to destination file:
                pw = new PrintWriter(new PrintStream(new FileOutputStream(destinationFile)));
                Iterator iterator = treeSet.iterator();
                while (iterator.hasNext()) {
                    pw.println(iterator.next());
            } finally {
                if (br != null) {
                    br.close();
                if (pw != null) {
                    pw.close();
        }//else: sourceFile unavailbel
    }//sortFile()

Similar Messages

  • How to sort source file beforfe mapping

    Dear all,
    Its a file (fixed length) to Idoc(FIDCC1) scenario.
    Source file has the following fields:
    Date
    Account
    Cost Center
    Debit Amount
    Credit Amount
    Etablissement
    The mapping requirement is:
    1. Per 'Etablissment' code, an Idoc(FIDCCP01) has to be generated.
    2. Per IDOC, segment E1F1SEG has to be created for each line in flat file, for their respective etablissment code.
    Per line in the flat file the difference    between the debit and credit amount is the amount that has to be posted per segment (posted amount is always positive). If zero no segment is created          
    3. Date and Account fields would go into fields in segment E1FIKPF, this segment will not repeat, there'll be only one segement per idoc (like header data)
    Now the issue is:
    The source file is not sorted per etablissment code.
    Etablissment can has value 001 in 1st and 3rd record and 002 in 2rd and 4th record.  in this case, We need to create 2 idocs, 1 for code 001 and another for 002. Each IDOC should have 2 segments of E1FISEG, corresponsding to their etablissment code.
    then for each idoc, the first record details should go to E1FIKPF segment of idoc.
    I could create Idoc based on code, by the following mapping,
    Etablissmentcode -> remove context -> sort -> split by value (value changed) -> collapse context -> IDOC
    But i'm cluless as to how to go about with the logic of E1FISEG segment creation and populating other fields of E1FIKPF.
    Please help me out. Is it achievable thruogh graphical mapping?

    Hi ,
    Please use  the below logic for mapping
    1. for creating IDOC=
    Etablissement>sort>splitbyvalue(value change)>collapse contextIDOC
    2. to create as many segment as of number of line item
    Etablissement>sort>splitbyvalue(value change)-segment
    3. foe each element under the segment
    Etablissement>sort bye key>splitbyvale(each value)--> corresponding account at IDOC
            Account-->
    hope this will solve you problem.
    thanks
    Navneet

  • How to sort files by TimeStamp.

    Hello friends,
    I have files which has following format.
    Paymentxxxx.xml where xxxx is time in YYYYMMDDHH:MM:SS format.Example file name can be
    Payment20010726143455.xml.How to sort such files according to time so that i can get old files first.
    Thanks

    <pre>
    import java.util.*;
    import java.text.*;
    class Timing
         public static void main(String[] args)
              try
              SimpleDateFormat sdf=new SimpleDateFormat();
              String formatter="yyyyMMddhhmmss";
              sdf.applyPattern(formatter);
              //Accept files names here , and deduct extension and pass them into array as following
              String[] inputdates={"19760909132332","19760909032332","19830901132332","19800909132332"};
              Date[] conversionDate=new Date[inputdates.length];
              for(int i=0;i<inputdates.length;i++)
                   conversionDate=sdf.parse(inputdates[i]);
              Date[] outputDates=sortDates(conversionDate);//Sorting dates
              for(int i=0;i<outputDates.length;i++)
              System.out.println(outputDates[i]);//CONVERT DATES INTO STRINGS
              catch(Exception e)
         private static Date[] sortDates(Date[] dates)
              int COUNT = dates.length;
              int j;
              Date tempDate;
              for(int i=0;i<COUNT;i++)
                   j=i-1;
                   tempDate=dates[i];
                   while(j>=0 && tempDate.before(dates[j]))
                        dates[j+1]=dates[j];
                        dates[j]=tempDate;
                        j--;
              return dates;
    </pre>

  • PSE6 - sort by file name

    How to sort by file name in the Organize view of PSE6.
    I tried Display->Folder Location. But there are still two pictures (#15 and #18 out of 130) which are shown at the end of the view.
    More sort options in the thumbnail view would be helpful.
    Thanks
    Hagen

    Not sure I understand what zou mean here Hagen. Do you because the
    images are in a different folder they don't end up in the right sequence?
    Put requests into the Feature Request area by the way. Forum
    participants are end-users like yourself.
    Cheers

  • How to sort files and folders like Windows

    I don't know if this is specific to Arch or every other Linux distro but one thing that really bugs me in Arch is how files and folders are sorted. I use Windows as my main OS (don't start on that please) and I have one folder properly organized exactly as I want it and I like it how Windows sorts this. I access that same folder from my Arch installation, the problem is that the sorting is different and it gets on my nerves lol...
    This is how Windows sorts that specific folder:
    C:\Users\Nazgulled\Documents\University>dir /O
    Volume in drive C is Vista
    Volume Serial Number is F84E-02BE
    Directory of C:\Users\Nazgulled\Documents\University
    05-08-2009 15:34 <DIR> .
    05-08-2009 15:34 <DIR> ..
    05-08-2009 11:10 <DIR> [Archives]
    05-08-2009 14:38 <DIR> [Developers]
    05-08-2009 11:17 <DIR> [X] 1) Cálculo II
    05-08-2009 11:18 <DIR> [X] 2) Análise de Custos
    05-08-2009 11:18 <DIR> [X] 2) Cálculo de Programas
    05-08-2009 11:18 <DIR> [X] 2) Laboratórios de Informática III
    05-08-2009 11:18 <DIR> 2) Algoritmos e Complexidade
    05-08-2009 11:18 <DIR> 2) Arquitectura de Computadores
    05-08-2009 11:18 <DIR> 2) Comunicaçao de Dados
    05-08-2009 11:18 <DIR> 2) Engenharia Económica
    05-08-2009 11:18 <DIR> 2) Estatística Aplicada
    0 File(s) 0 bytes
    13 Dir(s) 24.700.485.632 bytes free
    And this is how Arch does it:
    nazgulled ~/University $ ls -l
    total 7
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Algoritmos e Complexidade
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Arquitectura de Computadores
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Comunicação de Dados
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Engenharia Económica
    drwxr-xr-x 1 nazgulled nazgulled 8192 2009-08-05 11:18 2) Estatística Aplicada
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:10 [Archives]
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 14:38 [Developers]
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:17 [X] 1) Cálculo II
    drwxr-xr-x 1 nazgulled nazgulled 12288 2009-08-05 11:18 [X] 2) Análise de Custos
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 [X] 2) Cálculo de Programas
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 [X] 2) Laboratórios de Informática III
    How can I get Arch/Linux to sort exactly the same as Windows?
    Last edited by Nazgulled (2009-08-05 14:41:47)

    toad wrote:
    Nazgulled wrote:Surely there must be a way to have the same sorting collation in Linux like in Windows
    Ah, no. The way they are doing it is nonsensical and not good practice for a unix style system. Having said that, some solutions have already been offered in this thread.
    While you are free to continue to ask others to help you achieve your aims, it may be more convenient for you to adapt to a structure that is displayed the same way under all systems (just to avoid frustration - not saying you _should_ do it ).
    I really don't care if it's nonsensical, I use Windows 95% of the time or more, it's my main OS, I'm used to it and I like it. Why should I care if it's not a good practice for a unix style system? I just want things to behave the way I like and for a free system like Linux where it doesn't even compare to Windows in terms of freedom in what I can do with it and configure the way I like, it sure is hard to change the way folders/files are sorted...
    It sucks that there isn't a proper solution but I'm not going to adapt anything, that would be nonsensical... But if I have to, I can live with the fact that there isn't a good solution and leave it as it is
    Thanks everyone for their input, "topic closed".

  • How can I have uploaded pictures to iPhone or iPad be sorted by file name. Used to be able to based on their folders, but it no longer works and puts pictures in random order, I guess by date, which doesn't work for me. Need them by file name.

    Using windows. In the past I was able to have the picutres sorted in files and by file name and that is how they showed in the phone or pad. Not long ago one of the itune updates changed so it sorted by date and the the another update changed so it went by file name. Well when I got a new computer and updated itunes it won't load pictures in correct order. Is there an option I'm missing or is this an option that Apple should have for how you want pictures sorted?

    SELECT     datapoint,
               sub_total,
               section
    FROM       report_table
    WHERE      datapoint IN
                   (SELECT   datapoint
                    FROM     report_table
                    WHERE    section IN ('027', '038', '042', '044', '006', '008', '011', '022', '023')
                    AND      report_name = :selected_report_name
                    GROUP BY datapoint
                    HAVING SUM(CASE WHEN section IN ('027', '038', '042', '0440') THEN 1 ELSE 0 END)
                        <> SUM(CASE WHEN section IN ('008', '011', '022', '023') THEN 1 ELSE 0 END))
    ORDER BY   datapoint;

  • How to sort Data in XML template (rtf) file?

    Hi, I have an oracle 11i custom report (rdf) with an xml output to a PDF. There is a formula column in the report. Now I need the data to be sorted on this formula column. As we cannot sort on formula column, i have decided to find a way to sort it in the data in the XML template. But I don't really know how to sort and also where to specify the sort tag in the rtf file. I appreciate your response.
    Databse version : 9.2.0.8.0
    E-Biz Version : 11.5.10.2
    Oracle Reports Version : 6.0.8.27.0
    Oracle BI version : 10.1.3.2.1
    Note : I posted this question under : XML General forum also. But did not get any response. I assumed that may be thats not the right place to post it as my report is in e-Biz environment.

    Hi
    As long as you don't have your ^field commands grouped inside a ^group the order in the .dat file is not important. Your last command
    ^field BG_DOC_LN__LN_AM
    246624.12
    should populate field BG_DOC_LN_AM wherever you place it on your form. Obviously you need to name the fields according to your ^field commands and not just use tab (move to next field).
    Shout if this was not what you are asking.
    Stale Sodal

  • How I can sort music files (audiobook) in music player on iPhone by file name, not by title name?

    I have audiobook of abt.500 files, all titles are the name of the book. iPhone music player does not understand sorting by file names, but by title, hterfore it plays files chaotic. So, how I can sort audiobook files in music player by file name, not by title name?

    I have the same problem.
    I've went through the pains of merging all chapters into one big file for each and every audiobook, so that at least the chapters don't get played in random order. Month and month of work….. In iTunes 12.01. I can now order my audiobooks by title or by author.
    But once they're uploaded to my blo*dy expensive iPhone 6Plus 128 (which I bought especially to have all my music and my audiobooks on one device) my audiobooks are NOT sorted by author, but by Title.
    So, let's say I have 15 books by Ken Follet, they don't appear as Ken Follet > Title of the book but they are sorted alphabetically with all the other titles of other authors.
    iPods where originally designed for music and audiobooks, but each and every version of iOS makes handling your music and especially your audiobooks harder and harder….
    I am very disappointed and after so many years of using apple, I am considering to move on to android devices.

  • How to sort video by file name in Event Library?

    How to sort? so that I many all clips sorted by name and can drag them all to my project to create quick movie that has correct date and time sequence, as the file name.
    Thanks!

    I cannot figure out how to sort the clips either....

  • How do i sort by (file) name

    How do i sort by file name for an album?  I organize the photos from all different sources.. by filename.. and when i import them i just want them in the right order.  This has to be one of the most basic functions and why was it eliminated from iPhoto?
    Now all i get is "keep sorted by date" check box... (which does not work, some are still not in order)
    Apple:  this minimalist crap is getting old.. THIS IS A desktop PC..not an ipad or iphone.  Put some meat in the menus and stop worrying so much about everything being pretty and streamlined. 
    C'mon!!!.. wasted time

    Now all i get is "keep sorted by date" check box... (which does not work, some are still not in order)
    "Keep sorted by date" can only be toggled on and off for regular albums, not for smart albums.

  • How do I get my photos to sort by file name when sync'd to the iPad?

    How do I get my photos to sort by file name when sync'd to the iPad?  The default sorting method changes the order of pictures when sync'd from my pc.

    http://support.apple.com/kb/HT4221

  • How to Sort music on play list by FILE NAME?

    How to Sort music on play list by FILE NAME?

    iTunes doesn't display the filename or filepath as a column so you can't sort on it. I could write a script to copy the filepath into the Sort Name field so that sorting by name would sort by filepath. Would that help? In normal circumstances however filepath order would be the same as Album by Artist, so I'm not sure what you would gain. Perhaps there is another way to approach whatever problem you think sorting by filename would solve.
    tt2

  • How do I sort by file type?

    I was wondering how I can sort by file type?  I have a bunch of .moi and .mod files in a directory and want yo delete the .moi files.  If I could sort by type, then it would just be a matter of highlighting those and deleting. I tried sorting by kind, but since they are seen as Unix Executable files by the OS, it sorts them but not by .moi or .mod.  Thanks in advance for your help.
    MAC OS 10.6.8

    I don't believe you can sort by extension.  However, what you can do is to type .moi into the search field at the top of the Finder window where you see those files.  That will initially show all .moi files on your entire computer.  At the top of the displayed search results will the the text "Search:" followed by three choices.  "This Mac" should be selected, but the name of the folder you were looking in will be the second choice...  click that one.  That will cause the search results to contain only files from that folder, containing the text ".moi", which should be the ones you're interested in deleting.

  • What sort of file or item is storaged in Others and how to delete them?

    What sort of file or item is storaged in Others and how to delete them?

    See here for answer about the OTHER which is taking up space:
    http://pondini.org/TM/30.html
    and here:
    http://pondini.org/OSX/DiskSpace.html
    See Kappys excellent note on the rest of “other” files taking up your space:
    What is "Other" and What Can I Do About It?

  • How do I sort iPhoto files by size?

    How do I sort iPhoto files by size?

    Dear TD,
    (I like another person's reference to iTunes)
    My problem is that in moving a large number of photos from iPhoto to a thumb drive, on inspecting the latter I found many to be size 4K with no openable content.  This is a waste of resources.  It would have been very convenient to have been able to sort within iPhoto.
    I solved the problem by sorting the files on the thumb drive, getting rid of the size 4K files, deleting the album on iPhoto, and reloading them to a new album in iPhoto -- a lot of trouble, and nervous-making when moving around so many cherished photos.  (Of course... I have backups.)
    Also, since I haven't posted to the forums (fora?) in a while, the description of my gear doesn't reflect that I'm now using Yosemite. Nice upgrade!
    Another TD

Maybe you are looking for

  • Not Able to use BBC Iplayer

    Still cannot reliably use Iplayer. It has improved but still not correct. Can anyone help. Stats below FAQ 1. Best Effort Test:  -provides background information. Download  Speed 1.97 Mbps 0 Mbps 2 Mbps Max Achievable Speed  Download speedachieved du

  • 50D "freezing" when using an external shutter release..

    Hello photo friends. I have developed an issue with my 50D. I shoot exclusively landscape photography,(large f-stops, long shutter speeds) and use an external shutter release most of the time. However, recently, after a few exposures, my camera "free

  • Solaris 10 hang during boot

    Don't know if this is a right place, if it's not, please direct me, thanks! I had a SPARC Ultra 10 machine running under Solaris 10, it was running for couple months. Recently when I reboot it, it was hang at "Use is subject to license terms." I pres

  • Ace module dropping assymetric layer 2 connections

    Hi we had a situation in where the ACE would randomly drop certain tcp connections, and all ICMP packets from a certain windows server.  The server in question was using Transmit Load Balancing with Fault Tolerance. The server has one Nic connected t

  • Want to transfer pics to my Win 7 Photo Stream folder from my ipad

    I have taken pictures on my iPad that are in "my photo stream" on my iPad. I would like them to be wireless  transferred to my photo stream folder automatically on my Windows 7 PC. I can attach my iPad to my computer,copy all the pictures and paste t