logo
down
shadow

Sort file based on date in file name


Sort file based on date in file name

By : user2185604
Date : November 22 2020, 04:01 AM
help you fix your problem I need to sort files with respect to their date in the file name. I have written code which sorts the files but not running as expected. , Just replace below line:
code :
return o1Date.compareTo(o2Date);
return o1Date.replace("-", "_").compareTo(o2Date.replace("-", "_"));
    Pattern pattern=Pattern.compile(".*_([0-9_]{10}.*)\\..*");
    public static String extractDate(String in)
     {
         Matcher m=pattern.matcher(in);
         if(m.matches())
            return m.group(1);

         return in;
     }
return extractDate(o1.getName()).compareTo(extractDate(o2.getName());


Share : facebook icon twitter icon
Sort file based on date using Java

Sort file based on date using Java


By : Janei Guimarães
Date : March 29 2020, 07:55 AM
it should still fix some issue If you want something a little bit more robust than just sorting by name (which should indeed work for the sample filenames you provided), you should parse the date in the filename and sort by this date. For instance:
code :
public int compare(File f1, File f2)
{
    Date d1 = fileNameToDate(f1);
    Date d2 = fileNameToDate(f2);
    return d1.compareTo(d2);
}

//caution: this static is better for performance, but may not be thread-safe
private static SimpleDateFormat DF_YYYYMMDD = new SimpleDateFormat("yyyyMMdd");

private Date fileNameToDate(File f)
{
   int pos = f.getName().lastIndexOf('_');
   if (pos < 0)
   {
     //TODO: error handling if filename is not in the correct format
   }
   String dateStr = f.getName().substring(pos + 1, pos + 1 + 8);
   try
   {
     return DF_YYYYMMDD.parse(dateStr);
   }
   catch(ParseException e)
   {
     //TODO: error handling if filename is not in the correct format        
   }
}
Java sort a csv file based on column date

Java sort a csv file based on column date


By : damnya
Date : March 29 2020, 07:55 AM
hope this fix your issue Is not safe to remove an item inside of a loop. You have to iterate array over Iterator, for example:
code :
List<String> names = ....
Iterator<String> i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   // Do something
   i.remove();
}
How to sort the text file records based on date time

How to sort the text file records based on date time


By : user3613411
Date : March 29 2020, 07:55 AM
will be helpful for those in need The trick is to first annotate each line with a python-readable timestamp and then sorting this list of annotated lines.
I have put some sample code below:
code :
import time
import re

def parse_line(line):
    """
    Parses each line to split line into the timestamp and the rest
    """

    line = line.rstrip()
    m = re.match(r"(\w{3}\s+\d+\s+[0-9:]+)\s+(.*)", line)
    if m:
        timestamp = time.strptime(m.group(1), "%b %d %H:%M:%S")
        return (timestamp, line)


def main():
    f = open('input_msg.txt', 'r')
    lines = []
    for line in f:
        parsed = parse_line(line)
        if parsed:
            lines.append(parsed)
    # sort the array based on the first element of each tuple
    # which is the parsed time
    sorted_lines  = sorted(lines, key=lambda annotated_line: annotated_line[0])
    for l in sorted_lines:
        print l[1]

if __name__ == "__main__":
    main()
python sort file based on created date

python sort file based on created date


By : 4bsolute
Date : March 29 2020, 07:55 AM
this one helps. Here is the program with some nice printing using the format function:
code :
import os
import time

path = os.getcwd()

def file_info(directory):
    file_list = []
    for i in os.listdir(directory):
        a = os.stat(os.path.join(directory,i))
        file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
    return file_list


file_list = file_info(path)

for item in file_list:
    line = "Name: {:<20} | Last Accessed: {:>20} | Date Created: {:>20}".format(item[0],item[1],item[2])
    print(line)
import os
import time

path = os.getcwd()

def file_info(directory,sortLastModifiedOrNaw=False):
    file_list = []
    currentMin = 0 #This is the variable that will track the lowest digit
    for i in os.listdir(directory):
        a = os.stat(os.path.join(directory,i))
        if sortLastModifiedOrNaw == True: #If you would like to sort.
            if a.st_atime > currentMin: #Check if this is bigger than the current minimum. 
                currentMin = a.st_atime #If it is we update the current minimum
                #Below we append so that it ends up in the end of the list
                file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
            else: #If it is smaller, it should be in the front of the list so we insert it into position 0. 
                file_list.insert(0,[i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
        else: #If you would not like to sort
            file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
    return file_list


file_list = file_info(path)

print("Unsorted Example")
for item in file_list:
    line = "Name: {:<20} | Date Last Accessed: {:>20} | Date Created: {:>20}".format(item[0],item[1],item[2])
    print(line)

print("\nSorted example using last modified time")
file_list = file_info(path,sortLastModifiedOrNaw=True)

for item in file_list:
    line = "Name: {:<20} | Date Last Accessed: {:>20} | Date Created: {:>20}".format(item[0],item[1],item[2])
    print(line)
Unsorted Example
Name: .idea                | Date Last Accessed: Sun Jan  3 21:13:45 2016 | Date Created: Sun Jan  3 21:13:14 2016
Name: blahblah.py          | Date Last Accessed: Sun Jan  3 21:13:48 2016 | Date Created: Sun Jan  3 21:13:48 2016
Name: testhoe1.py          | Date Last Accessed: Sun Jan  3 19:09:57 2016 | Date Created: Sun Jan  3 18:52:06 2016

Sorted example using last modified time
Name: testhoe1.py          | Date Last Accessed: Sun Jan  3 19:09:57 2016 | Date Created: Sun Jan  3 18:52:06 2016
Name: .idea                | Date Last Accessed: Sun Jan  3 21:13:45 2016 | Date Created: Sun Jan  3 21:13:14 2016
Name: blahblah.py          | Date Last Accessed: Sun Jan  3 21:13:48 2016 | Date Created: Sun Jan  3 21:13:48 2016
Sort a file based on first date time column

Sort a file based on first date time column


By : unreal
Date : March 29 2020, 07:55 AM
will be helpful for those in need You're in luck. Assuming all your dates are ISO style, you should be able to just run sort -k 1,2 test.txt, where -k option specifies you are sorting on first 2 collumns (in given order).
Related Posts Related Posts :
  • Return page object from JPA query
  • I can't figure out why this code in my APCS multiple choice book returns 19
  • How to save data between methods
  • I'm trying to install Apache Gobblin. How can I install it using Gradle?
  • Spring Data Sorting Array or Set into Pageable
  • Question about the Java documentation and its implementation
  • How to make a JButton that when pressed it does a new action
  • Java hibernate No validator could be found for boolean
  • Making a POJO Thread Safe
  • Save the data of a text file in a arraylist
  • Sort a List<String[]> by indices using Comparator
  • Overloading in Java for user input?
  • Unable to format timestamp as YYYY-MM-DD HH:mm:ss in java
  • Access SQLite Helper From Adapter
  • How to stream a csv file with header to a HashMap<String, Double> in Java?
  • can't get go daddy ssl certificate to work with spring boot
  • ResourceBundle can't find BaseName gradle project java
  • Java; Jackson; Parsing the array of array json string
  • Java - map key lookup ignoring case
  • Jackson deserialize map null values to empty string
  • Anyone knows why setCount() is not working in twitter4j?
  • Object Visibility in a Multi-threaded Program in Java
  • Can't store and load an arraylist in an object file
  • convert a string number starts with `00` to `+` in java
  • Java - avoiding NonSuchElementException using ConcurrentLinkedDeque
  • Converting Immutable to mutable list Java
  • Getting nosuchmethod exception
  • How to get MQTT subscriptions
  • Android Google Sign in Exceptions
  • JavaFX - method that waits for user input
  • Replacing values for a particular key in treemap changes values for every key
  • This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter th
  • Kafka: consume all messages on demand
  • Notify what text was changed in textview
  • Tinkerpop/Gremlin: select vertices together with outgoing edge count
  • transform a list of objects into a list of integers that pass a check
  • Why this java code is showing strange behavior?
  • Maven Project classes not compiling
  • Edit image to make text more clear opencv
  • Android Spinner nullpointer
  • Add result to int array every time you finish counting the occurrence
  • Android import java library
  • How to use LDAP Authentication in a corporate environment
  • adding item during iteration in java special usecase
  • How can I sort a map with string key? like (1 foo , 2 foo)
  • How to test an implementation of TLS based on SSLEngine?
  • Sorting a Linked List in alphabetical order
  • Can't make more than one request on java.net.http.HttpClient or will receive: javax.net.ssl.SSLHandshakeException
  • Java logic - strange things happening in while loop
  • Unable to replicate an encryption method from Java to PHP using AES/ECB/PKCS5Padding
  • How program arithmetics on general objects which become defined only later?
  • Make asynchronous call synchronous in Kotlin
  • Thread Pool with Spring @Value for Pool size doesnt run properly
  • How to substring before nth occurence of a separator?
  • Resume S3 multipart upload: PartETag
  • Mutable fields should not be "public static"
  • How to remove fragment from URI
  • Add a node in xml using java only if the node has an attribute
  • java streams: elegant way to filter according an exception is thrown
  • Exception in thread, java code wont execute properly. If/else statments
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org