Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Friday, February 10, 2017

VBScript Delete All Files And SubFolders

VBScript is a scripting language to manage computer developed by Microsoft. It is important that we have power to do something using some script written by me. Below is a code snippet that delete all files & subfolders & files of subfolders easily.

Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder("C:\tmp\xxx")

'Delete all files in root folder
for each File in Folder.Files
    On Error Resume Next
    name = File.name
    File.Delete True
    If Err Then
        WScript.Echo "Error deleting:" & Name & " - " & Err.Description
    Else
        WScript.Echo "Deleted:" & Name
    End If
    On Error GoTo 0
Next

'Delete all subfolders and files
For Each File In Folder.SubFolders
    On Error Resume Next
    name = File.name
    File.Delete True
    If Err Then
        WScript.Echo "Error deleting:" & Name & " - " & Err.Description
    Else
        WScript.Echo "Deleted:" & Name
    End If
    On Error GoTo 0
Next

Saturday, December 17, 2016

How to convert Map / Object to Bytes and save to internal storage and read back

package com.pkm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author PRITOM
 */
public class MapObjectToByteArrayAndSaveToFile {
    public static void main(String[] args) throws Exception {
        Map<Integer, String> data = new HashMap<Integer, String>();
        data.put(1, "hello");
        data.put(2, "world");
        System.out.println(data.toString());
        store(data);
        data = (Map<Integer, String>) load();
        System.out.println(data.toString());
    }
    
    public static Object load() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("object.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        return objectInputStream.readObject();
    }
    
    public static void store(Object data) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("object.txt");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(data);
        outputStream.close();
    }
}

Monday, September 26, 2016

File Change Listener Implementation Using Java


package com.pritom.kumar;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

/**
 * Created by pritom on 25/09/2016.
 */
public class ChangeFileListener {
    public static void main(String[] args) throws Exception {
        startWatch("C:/tmp");
    }

    public static void startWatch(String location) {
        try {
            Path directory = Paths.get(location);
            println("Start listening directory: [" + location + "]");
            final WatchService watchService = directory.getFileSystem().newWatchService();
            directory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

            while (true) {
                final WatchKey watchKey = watchService.take();
                handleWatchTriggered(location, watchKey);
                boolean valid = watchKey.reset();
                if (!valid) {
                    throw new Exception("Watcher failed for listen [" + location + "]");
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void handleWatchTriggered(String location, WatchKey watchKey) throws Exception {
        List<WatchEvent<?>> watchEventList = watchKey.pollEvents();
        for (WatchEvent watchEvent : watchEventList) {
            if (watchEvent.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                println("Created: [" + watchEvent.context().toString() + "]");
                File fileCreated = new File(location + "/" + watchEvent.context().toString());
            }
            else if (watchEvent.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                println("Deleted: [" + watchEvent.context().toString() + "]");
            }
            else if (watchEvent.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                println("Modified: [" + watchEvent.context().toString() + "]");
            }
        }
    }

    public static void println(Object o) {
        System.out.println("" + o);
    }
}

Tuesday, June 28, 2016

Java Convert File Into Bytes (Array of Bytes)


package com.pritom.kumar;

import java.io.File;
import java.io.FileInputStream;

/**
 * Created by pritom on 28/06/2016.
 */
public class ReadFileAsByteArray {
    public static void main (String[] args) throws Exception {
        File file = new File("x1.zip");

        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        System.out.println("File_Length=" + file.length() + ", Byte_Length=" + toByte.length + ", Both_Are_Equal=" + (file.length() == toByte.length ? "True" : "False"));
    }
}


Output:

File_Length=14805774, Byte_Length=14805774, Both_Are_Equal=True

Monday, August 11, 2014

Cross-platform way of working with python temporary file and directory

import tempfile
import os

print 'Temp Directory:', tempfile.gettempdir()
f = tempfile.NamedTemporaryFile(delete=False, prefix='_PREFIX_', suffix='_SUFFIX_')
print 'File Name:', f.name;
f.write('Something On Temporary File... 1')
f.write('\nSomething On Temporary File... 2')
f.seek(0)
print '\nFile Contents: '
print f.read()
print '\nFile Contents Line By Line: '
f.seek(0)
for line in f:
    print '--->', line.rstrip()
f.close()
print '\nFile Exists:', os.path.exists(f.name)
os.unlink(f.name)
print '\nFile Exists:', os.path.exists(f.name)
dirc = tempfile.mkdtemp()
print '\nDirectory Name:', dirc
print '\nDirectory Exists:', os.path.exists(dirc)

for num in range(1, 3):
    fname = os.path.join(dirc, str(num) + '.file');
    print '\nCustom File:', fname
    tpfile = open(fname, 'w+b');
    tpfile.write('Writting Something...' + str(num));
    tpfile.seek(0);
    print 'File Contents:'
    print tpfile.read();
    tpfile.close()
    print 'File Exists:', os.path.exists(tpfile.name)
    os.unlink(tpfile.name)
    print 'File Exists:', os.path.exists(tpfile.name)

print '\nDirectory Name:', dirc
print '\nDirectory Exists:', os.path.exists(dirc)
os.removedirs(dirc)
print '\nDirectory Exists:', os.path.exists(dirc)

Output would be like this:

Temp Directory: c:\users\user\appdata\local\temp
File Name: c:\users\user\appdata\local\temp\_PREFIX_mrr8st_SUFFIX_

File Contents: 
Something On Temporary File... 1
Something On Temporary File... 2

File Contents Line By Line: 
---> Something On Temporary File... 1
---> Something On Temporary File... 2

File Exists: True

File Exists: False

Directory Name: c:\users\user\appdata\local\temp\tmpdvd8ej

Directory Exists: True

Custom File: c:\users\user\appdata\local\temp\tmpdvd8ej\1.file
File Contents:
Writting Something...1
File Exists: True
File Exists: False

Custom File: c:\users\user\appdata\local\temp\tmpdvd8ej\2.file
File Contents:
Writting Something...2
File Exists: True
File Exists: False

Directory Name: c:\users\user\appdata\local\temp\tmpdvd8ej

Directory Exists: True

Directory Exists: False

Monday, August 19, 2013

How can I upload files asynchronously with jQuery


With HTML5 you CAN make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress eventwith the HTML5 progress tag (or a div).

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

<div class="progress_bar"
     style="width: 300px; height: 20px; background-color: blue; position: relative;">
    <div class="full" style="width: 0%;
    height: 20px; background-color: red;"></div>
    <div class="text"
         style="color: #ffffff; font-weight: bold; text-align: center;
         position: absolute; left: 109px; top: 0;">Uploading...</div>
</div>
<script type="text/javascript">
    jQuery(document).ready(function() {
        $(':button').click(function(){
            var formData = new FormData($('form')[0]);
            $.ajax({
                url: 'upload.php',  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: function() {
                    console.log("Before send...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.full").css({
                        width: "0%"
                    });
                },
                success: function(data) {
                    console.log(data);
                    console.log("Success...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.text").html("Uploaded.");
                },
                error: function() {
                    console.log("Error...");
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });
    function progressHandlingFunction(e){
        console.log(e);
        if(e.lengthComputable){
            var $div = jQuery("div.progress_bar");
            var p = e.loaded / e.total * 100;
            $div.find("div.full").css({
                width: p + "%"
            });
            console.log(p);
        }
    }
</script>


As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser. 

Thursday, June 27, 2013

Output or echo an Image or File using PHP script

$file = 'image.jpg'; 
 
$obj = header($file);
if(isset($obj["mime"])) {
    header('Content-Type:'.$obj["mime"]);
} else {
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
}

header('Expires: 0');
header('Pragma: public');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Content-Disposition: inline; filename="some name.jpg" ');  
header('Content-Length: ' . filesize($file));

readfile($file);
exit;

Thursday, June 13, 2013

jQuery clear a file input field

<input type="file" id="control"/>
<button id="clear">Clear</button>

var control = $("#control");

$("#clear").on("click", function () {
    control.replaceWith( control = control.clone( true ) );
});

Friday, February 1, 2013

get file size by jquery before upload

You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {

  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);

});
As it is a part of the HTML5 specification, it will only work for modern browsers (and IE is not one of them).

Friday, December 14, 2012

Java: Reading and writing text files

package pritom;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 14/12/12
 * Time: 9:28 AM
 * To change this template use File | Settings | File Templates.
 */
public class ReadWriteTextFileJDK7 {

    public static void main(String... aArgs) throws IOException {
        ReadWriteTextFileJDK7 text = new ReadWriteTextFileJDK7();

        //treat as a small file
        List<String> lines = text.readSmallTextFile(FILE_NAME);
        log(lines);
        lines.add("This is a line added in code.");
        text.writeSmallTextFile(lines, FILE_NAME);

        //treat as a large file - use some buffering
        text.readLargerTextFile(FILE_NAME);
        lines = Arrays.asList("Line added #1", "Line added #2");
        text.writeLargerTextFile(OUTPUT_FILE_NAME, lines);
    }

    final static String FILE_NAME = "C:/tmp/input.txt";
    final static String OUTPUT_FILE_NAME = "C:/tmp/output.txt";
    final static Charset ENCODING = StandardCharsets.UTF_8;

    //For smaller files

    List<String> readSmallTextFile(String aFileName) throws IOException {
        System.out.print("***** readSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        return Files.readAllLines(path, ENCODING);
    }

    void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        System.out.print("***** writeSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, ENCODING);
    }

    //For larger files

    void readLargerTextFile(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        Scanner scanner =  new Scanner(path, ENCODING.name());
        while (scanner.hasNextLine()){
            //process each line in some way
            log(scanner.nextLine());
        }
    }

    void readLargerTextFileAlternate(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFileAlternate *****\n");
        Path path = Paths.get(aFileName);
        BufferedReader reader = Files.newBufferedReader(path, ENCODING);
        String line = null;
        while ((line = reader.readLine()) != null) {
            //process each line in some way
            log(line);
        }
    }

    void writeLargerTextFile(String aFileName, List<String> aLines) throws IOException {
        System.out.print("***** writeLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        BufferedWriter writer = Files.newBufferedWriter(path, ENCODING);
        for(String line : aLines){
            writer.write(line);
            writer.newLine();
        }
        writer.flush();
    }

    private static void log(Object aMsg){
        System.out.println(String.valueOf(aMsg));
    }

}
http://www.javapractices.com/topic/TopicAction.do?Id=42 

Wednesday, December 5, 2012

Java check if file exists on remote server using its url

import java.net.*;
import java.io.*;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(URLUtils.exists("http://www.test.com/exists.html"));
    System.out.println(URLUtils.exists("http://www.test.com/no_exists.html"));
    /*
      output :
        true
        false
    */    
  }

  public static boolean exists(String URLName){
    try {
      HttpURLConnection.setFollowRedirects(false);
      // note : you may also need
      //        HttpURLConnection.setInstanceFollowRedirects(false)
      HttpURLConnection con =
         (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
       e.printStackTrace();
       return false;
    }
  }
}
 
 
The following is doing the same thing but this time we identify ourself to a proxy.
See also this HowTo.
 
import java.net.*;
import java.io.*;
import java.util.Properties;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(exists("http://www.your_server.com"));
    System.out.println(exists("http://www.yahoo.com"));
  }


  public static boolean exists(String URLName){
    try {
      Properties systemSettings = System.getProperties();
      systemSettings.put("proxySet", "true");
      systemSettings.put("http.proxyHost","proxy.mycompany.local") ;
      systemSettings.put("http.proxyPort", "80") ;

      URL u = new URL(URLName);
      HttpURLConnection con = (HttpURLConnection) u.openConnection();
      //
      // it's not the greatest idea to use a sun.misc.* class
      // Sun strongly advises not to use them since they can 
      // change or go away in a future release so beware.
      //
      sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
      String encodedUserPwd =
         encoder.encode("domain\\username:password".getBytes());
      con.setRequestProperty
         ("Proxy-Authorization", "Basic " + encodedUserPwd);
      con.setRequestMethod("HEAD");
      System.out.println
         (con.getResponseCode() + " : " + con.getResponseMessage());
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
}  

http://www.rgagnon.com/javadetails/java-0059.html