0

I am getting three different substrings from file ID's,company name and date

while retrieving i need to store sorted by date values into object.

I have retrieved and converted string to date format that i need and stored. instead of pulling again every time using sql sorting, trying to store sorted by dates before inserting.

class ReadingFile
{
    public static String input_path = ("C:\\Users\\RAVI\\Desktop\\Skills\\inputs");
    public static String output_path = ("C:\\Users\\RAVI\\Desktop\\Skills\\outputs");
    static BufferedReader br;
    void read(){
    SimpleDateFormat sdf = new SimpleDateFormat("hh:MM.ss");
    SimpleDateFormat parsingSdf = new SimpleDateFormat("hh:MM.ss a");
    ArrayList<Object[]> list = new ArrayList<Object[]>();
    try 
    {
    File fi = new File(input_path);
    File[] fileCount = fi.listFiles();
    for (int i = 0; i < fileCount.length; i++) 
        {
        File file = fileCount[i];
        if (file.isFile()) 
            {
            System.out.println("Total file count : " + fileCount.length);
            String fileName = file.getName();
            System.out.println("File name : " + fileName);
            String data;
            br = new BufferedReader(new FileReader(input_path + "\\"+ fileName));
            while ((data = br.readLine()) != null) 
            {
            if (data.contains(">")) 
                {
                Object[] received = new Object[3];
                String dat = data.substring(data.indexOf(" ") + 1,
                data.indexOf("-") - 1);
                // System.out.println(dat);
                Date date = sdf.parse(dat.substring(
                dat.indexOf(" "), dat.lastIndexOf(".")));
                // System.out.println(date);
                String timeFormat = parsingSdf.format(date);
                // System.out.println(timeFormat);
                received[0] = dat.substring(dat.indexOf("0"),dat.indexOf(" ") + 1)+ timeFormat;
                // System.out.println(received[0]);
                received[1] = data.substring(data.indexOf("<") + 1,data.indexOf(",") - 1);
                // System.out.println(received[1]);
                received[2] = data.substring(data.indexOf("Target"),data.lastIndexOf("."));
                //System.out.println(received[2]);
                list.add(received);
                }
            }
        }
    }

Sample input and respective output added below

input
(8834675) 06/01/2013 04:03.36.562 -->Successful password change for user=<U753838>, Password Target=<DOW>.
(8858218) 06/01/2013 07:18.42.312 -->Successful password change for user=<U640630>, Password Target=<DOW>.
(8893874) 06/01/2013 12:14.42.410 -->Successful password change for user=<U090521>, Password Target=<DOW>.

output

06/01/2013 04:03.36 AM U753838 Target=<DOW>
06/01/2013 07:06.42 AM U640630 Target=<DOW>
06/01/2013 12:02.42 AM U090521 Target=<DOW>
  • any sample of data, If you please – Sagar Kharab Feb 10 '19 at 18:11
  • Sure @SagarKharab –  Feb 10 '19 at 18:15
  • @SagarKharab i did edited and added sample i/o data, thanks –  Feb 10 '19 at 18:22
  • Oops..!! any idea.? –  Feb 10 '19 at 18:38
  • I am trying some program. I will post once ready. – Sagar Kharab Feb 10 '19 at 18:41
  • ok me too trying wether i can use map or comparator –  Feb 10 '19 at 18:47
  • https://stackoverflow.com/questions/14451976/how-to-sort-date-which-is-in-string-format-in-java This should help you! If not let me know. I have written some code. – Sagar Kharab Feb 10 '19 at 19:13
  • That is useful while sorting one column i assume but while sorting that other two columns should order accordingly to date, that's where i am struggling where to begin like that i am thinking again and again .awch..!! –  Feb 10 '19 at 19:17
  • refer to my solution if I got your issue correct. – Sagar Kharab Feb 10 '19 at 19:23
  • I am not able to execute your code it shows plenty of errors misplaced construct, and many variable forcing me to create class for that , for few i have imported packages rest not able to follow and fix bro –  Feb 10 '19 at 19:32
  • You have used many new things which version it belongs to i am new to Java –  Feb 10 '19 at 19:33
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 11 '19 at 01:54
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 11 '19 at 15:13
  • Is that a misunderstood attempt at optimization? SQL is great for sorting. Until you have ascertained that its sorting is taking too long, you should let it. – Ole V.V. Feb 11 '19 at 15:16
  • Related (but different): [How to get each column values from Object array stored in list [duplicate\]](https://stackoverflow.com/questions/54605574/how-to-get-each-column-values-from-object-array-stored-in-list) – Ole V.V. Feb 11 '19 at 15:18
  • in the link you added my same question as duplicate why @OleV.V. please check before you mark as duplicate –  Feb 14 '19 at 16:10
  • Sorry if I was unclear. I said “but different” exactly to say that this is *not* a duplicate. I just thought that having the background in your other question might be nice for some. I was completely aware that both questions were yours. – Ole V.V. Feb 14 '19 at 16:14
  • 1
    sorry @OleV.V. i would have included in that question itself but asking mutiple questions in same post would not be clear for many, that is the reason i have raised new question. leave it as, do you have any idea how to sort it ..? really appreciate for quoted . –  Feb 14 '19 at 16:21
  • Any clue how to achieve this..? –  Feb 14 '19 at 16:30
  • 1
    I did not see that. It exactly the same question, just without an accepted answer. – Jens Dibbern Feb 14 '19 at 18:29
  • Your requirements aren’t clear to me, do you need to sort the strings within the array or the arrays within the list? After the comments to the answer it’s also not clear whether the real problem is how to enable Java 8 features in your Eclipse. – Ole V.V. Feb 14 '19 at 18:43
  • Yes @OleV.V. we are in same project trying to fix it –  Feb 14 '19 at 18:52

3 Answers3

0

Please try this for once. Should do the deed.

public class FileWriter {
    public static void main(String[] args) throws Exception{
        try {
            BufferedReader br = new BufferedReader(new FileReader
                    (new File("Path of sample Data")));
            List<String> list = new ArrayList<>();
            br.lines().forEach(s -> {
                System.out.println(s);
                Arrays.stream(s.split("\\)")).skip(1).forEach(s1 -> {
                    String[] strArr = s1.split("-->");
                    String p2 = s1.split("=<")[1].split(">")[0];
                    String p3 = s1.split("Password")[1].trim();
                    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm.ss.SSS");
                    list.add(strArr[0].trim() + " " + p2 + " " + p3);
                    Collections.sort(list, (d1, d2) -> {
                        try{
                            return sdf.parse(d1.substring(0, 21)).compareTo(sdf.parse(d2.substring(0, 21)));
                        }
                        catch (ParseException e) {
                            e.printStackTrace();
                        }
                        return 0;
                    });
                });
            });
            list.stream().forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Sagar Kharab
  • 369
  • 2
  • 18
  • I am not able to execute your code it shows plenty of errors misplaced construct wherever you are using lamda expressions, and many variable forcing me to create class for that example s,s1,d1,d2 , for few i have imported packages rest not able to follow and fix bro –  Feb 10 '19 at 19:35
  • Are you not using Java 8?? – Sagar Kharab Feb 10 '19 at 19:49
  • java version "1.8.0_201" this is the version i m using –  Feb 10 '19 at 20:00
  • in eclipse compiler version indicates 1.7 –  Feb 10 '19 at 20:04
  • Compile and run with Java 8 please – Sagar Kharab Feb 10 '19 at 20:56
  • the option 1.8 not available to select bro, my bad –  Feb 10 '19 at 21:06
  • You should google it. You can find how to set the compiler level to 1.8 and then compile the code. Do some research around. – Sagar Kharab Feb 10 '19 at 21:48
  • I am not able to apply it as the version not supporting , is there any other clue you can give to apply in simple manner using either comparable or comparator –  Feb 14 '19 at 16:04
  • Any clue how to achieve this..? –  Feb 14 '19 at 16:31
0

An easy way is to use ISO date format like that:

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat iso = new SimpleDateFormat("yyyy-dd-MM");
...
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        while ((data = br.readLine()) != null) {
          if (data.contains(">")) {
            String[] parts = data.split(" ");
            Date date = sdf.parse(parts[1]);
            String newDate = iso.format(date);
            StringBuilder newLine = new StringBuilder(newDate);
            for (int i = 2; i < parts.length; i++) {
              newLine.append(" ").append(parts[i]);
            }
            System.out.println(newLine);
            list.add(newLine.toString());
          }
        }
        br.close();

This will result in

2013-06-01 04:03.36.562 -->Successful password change for user=<U753838>, Password Target=<DOW>.
2013-06-01 07:18.42.312 -->Successful password change for user=<U640630>, Password Target=<DOW>.
2013-06-01 12:14.42.410 -->Successful password change for user=<U090521>, Password Target=<DOW>.

which is easily sortable with Collections.sort(list);

Jens Dibbern
  • 1,434
  • 2
  • 13
  • 20
  • your sorting logic will do alone for date column right, but what we are seeking here is while you sorting by date respective strings stored in another object need to be sorted out , to be exact if you pull data from DB order by field value it should sort out entire table and produce output right likewise trying. –  Feb 14 '19 at 19:24
0
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class ReadingFile {
    public static String input_path = ("D:\\Aritra\\inputs");
    public static String output_path = ("D:\\Aritra\\outputs");
    static BufferedReader br;

    void read() {
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm.ss");
        SimpleDateFormat parsingSdf = new SimpleDateFormat("hh:mm.ss a");
        ArrayList<Object[]> list = new ArrayList<Object[]>();
        try {
            File fi = new File(input_path);
            File[] fileCount = fi.listFiles();
            for (int i = 0; i < fileCount.length; i++) {
                File file = fileCount[i];
                if (file.isFile()) {
                    System.out.println("Total file count : " + fileCount.length);
                    String fileName = file.getName();
                    System.out.println("File name : " + fileName);
                    String data;
                    br = new BufferedReader(new FileReader(input_path + "\\" + fileName));
                    while ((data = br.readLine()) != null) {
                        if (data.contains(">")) {
                            Object[] received = new Object[3];
                            String dat = data.substring(data.indexOf(" ") + 1, data.indexOf("-") - 1);
                            // System.out.println(dat);
                            Date date = sdf.parse(dat.substring(dat.indexOf(" "), dat.lastIndexOf(".")));
                            // System.out.println(date);
                            String timeFormat = parsingSdf.format(date);
                            // System.out.println(timeFormat);
                            received[0] = dat.substring(dat.indexOf("0"), dat.indexOf(" ") + 1) + timeFormat;
                            // System.out.println(received[0]);
                            received[1] = data.substring(data.indexOf("<") + 1, data.indexOf(",") - 1);
                            // System.out.println(received[1]);
                            received[2] = data.substring(data.indexOf("Target"), data.lastIndexOf("."));
                            // System.out.println(received[2]);
                            //list.add(received);
                            boolean isAdded = false;

                            if (!list.isEmpty()) {
                                Date currentEntry = new SimpleDateFormat("dd/MM/yyyy hh:mm.ss a")
                                        .parse((String) received[0]);
                                int count = 0;
                                do {
                                    Object[] loopElement =  list.get(count);
                                    Date loopElementDate = new SimpleDateFormat("dd/MM/yyyy hh:mm.ss a")
                                            .parse((String) loopElement[0]);
                                    int compareResult = currentEntry.compareTo(loopElementDate);
                                    if(compareResult<=0) {
                                        list.add(count,received);
                                        isAdded = true;
                                        break;
                                    } 
                                    count++;
                                } while (count < list.size());

                            }
                            if(!isAdded) {
                                list.add(received);
                            }       
                        }
                    }
                }
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("<<<<<<<<<<<<<< Result >>>>>>>>>>>>>>>>");
        for(Object[] l:list) {
            for(Object l1:l) {
                System.out.print("["+l1+"]");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        new ReadingFile().read();
    }
}
  • Kept your code almost the same. Changed hh:MM.ss to hh:mm.ss, and replaced "list.add(received);" with the additional block, where new element is compared with existing elements and inserted accordingly. – Aritra Kumar Dhawa Feb 14 '19 at 18:49
  • It is really working perfect, from 12AM to 4 AM and so on, this is what we need, thanks @Artitra Kumar –  Feb 14 '19 at 19:20
  • ANd why did you replaced hours, minutes and seconds to all lowercase , i mean what's wrong in keeping the same, it would cause any problem in sorting..? –  Feb 14 '19 at 19:26
  • Plz vote for my question to upvote your answers , thanks much...!! –  Feb 14 '19 at 19:39
  • Capital M is month. Small m is minute. – Aritra Kumar Dhawa Feb 14 '19 at 22:26
  • Why did you replaced its already declared correct right..? What does the difference does it make..?@Aritra Kumar –  Feb 15 '19 at 12:19
  • did not understand you question. Are you asking why I replaced "list.add(received);"? That is because instead of inserting directly in the list, I'm getting them compared with each element. I have not changed any declaration. You can try line-by-line comparison for better understanding. If you are asking about MM vs mm, that I have already explained, you can refer Java Doc for this. – Aritra Kumar Dhawa Feb 16 '19 at 07:23