Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

How to assign file content to a String in Java

Question:
How to copy the content of a file to a String using Java?

Code:
import java.io.DataInputStream;
import java.io.FileInputStream;
 
public class FileToString {
 
   public static void main(String args[]) {
 
      try {
 
         FileInputStream fis = new FileInputStream("/tmp/myfile.txt");
         DataInputStream dis = new DataInputStream(fis);
 
         byte[] data = new byte[dis.available()];
         dis.readFully(data);
         dis.close();
 
         String content = new String(data, 0, data.length);
 
         System.out.println(content);
 
      } catch (Exception ex) {
         System.out.println(ex);
      }
 
   }
}

Output:
$ java FileToString
This is an example on how to copy the contents of a file to a String using Java.



$ cat myfile.txt
This is an example on how to copy the contents of a file to a String using Java.

How to compress files in ZIP format in java?

Question:
How to compress files in ZIP format in java?

Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class CompressFile {
 
   public static void main(String[] args) {
 
      byte[] buffer = new byte[1024];
 
      try {
 
         FileOutputStream fos = new FileOutputStream("/tmp/myfile.zip");
         ZipOutputStream zos = new ZipOutputStream(fos);
         ZipEntry ze = new ZipEntry("myfile.txt");
         zos.putNextEntry(ze);
         FileInputStream in = new FileInputStream("/tmp/myfile.txt");
 
         int len;
         while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
         }
 
         in.close();
         zos.closeEntry();
 
         zos.close();
 
         System.out.println("Finished");
 
      } catch (IOException ex) {
         System.out.println(ex);
      }
   }
}

Output:
$ java CompressFile
Finished

$ ls -l /tmp/myfile.*
-rw-rw-r-- 1 dennis dennis 6880 Feb 27 06:37 /tmp/myfile.txt
-rw-rw-r-- 1 dennis dennis  178 Feb 27 06:39 /tmp/myfile.zip

How to get the total number of lines of a file in Java?

Question:
How to get the total number of lines of a file in Java?

Code:
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
 
public class CountLines {
 
  public static void main(String[] args) {
 
    try{
 
      FileReader fr = new FileReader("./CountLines.java");
      LineNumberReader lnr = new LineNumberReader(fr);
 
      int count = 0;
 
      while (lnr.readLine() != null){
        count++;
      }
      System.out.println("Total number of lines : " + count);
      lnr.close();
 
    } catch(IOException e) {
      System.out.println(e);
    }
 
  }
}

Output:
$ java CountLines
Total number of lines : 27

$ wc -l CountLines.java 
27 CountLines.java

How to decompress file from GZIP file using java?

Question:
How to decompress file from GZIP file using java?

Code:
import java.io.*;
import java.util.zip.GZIPInputStream;
 
public class GUnZipFile {
  public static void main( String[] args ) {
 
    String input = "/tmp/file.txt.gz";
    String output = "/tmp/file.txt";
 
    byte[] buffer = new byte[1024];
 
    try {
 
      FileInputStream fis = new FileInputStream(input);
      GZIPInputStream gzis = new GZIPInputStream(fis);
 
      FileOutputStream fos = new FileOutputStream(output);
 
      int len;
      while ((len = gzis.read(buffer)) > 0) {
         fos.write(buffer, 0, len);
      }
 
      gzis.close();
      fos.close();
      System.out.println("Done");
 
    } catch(Exception ex) {
      System.out.println(ex);
    }
  }
}

Output:
$ java GUnZipFile
Done

$ ls -l /tmp/file.txt.gz 
-rw-rw-r-- 1 dennis dennis 56 Feb 26 16:44 /tmp/file.txt.gz

$ ls -l /tmp/file.txt
-rw-rw-r-- 1 dennis dennis 4880 Feb 26 16:52 /tmp/file.txt

How to compress a file in GZIP format using java?

Question:
How to compress a file in GZIP format?

Code:
import java.io.*;
import java.util.zip.GZIPOutputStream;
 
public class GZipFile {
  public static void main( String[] args ) {
 
    String input = "/tmp/file.txt";
    String output = "/tmp/file.txt.gz";
 
    byte[] buffer = new byte[1024];
 
    try {
 
      FileInputStream in = new FileInputStream(input);
 
      FileOutputStream fos = new FileOutputStream(output);
      GZIPOutputStream gzos = new GZIPOutputStream(fos);
 
      int len;
      while ((len = in.read(buffer)) > 0) {
        gzos.write(buffer, 0, len);
      }
      in.close();
      gzos.finish();
      gzos.close();
      System.out.println("Done");
 
    } catch(Exception ex) {
      System.out.println(ex);
    }
  }
}

Output:
$ java GZipFile
Done

$ ls -l /tmp/file.txt
-rw-rw-r-- 1 dennis dennis 4880 Feb 26 16:42 /tmp/file.txt

$ ls -l /tmp/file.txt.gz
-rw-rw-r-- 1 dennis dennis 56 Feb 26 16:44 /tmp/file.txt.gz

How to check if a file is hidden in Java

Question:
How to check if a file is hidden in Java?

Answer:
Use the method isHidden() found in the class File.

Code:
import java.io.File;
import java.io.IOException;
 
public class HiddenFile {
 
   public static void main(String[] args) throws IOException { 
 
      File file = new File("/tmp/.hidden.txt");
 
      if(file.isHidden()) {
         System.out.println("File is hidden");
      } else {
         System.out.println("File is not hidden");
      }
   }
}

Output:
$ java HiddenFile
File is hidden

$ ls -l /tmp/.hidden.txt 
-rw-rw-r-- 1 dennis dennis 22 Feb 26 12:52 /tmp/.hidden.txt

How to change the file last modified date in Java?

Question:
How to change the file last modified date in Java?

Answer:
Use File.setLastModified()

Code:
import java.io.*;
import java.util.*;
import java.text.*;
 
public class ChangeModificationTime {
   public static void main(String[] args) {
      File file = new File("ChangeModificationTime.java");
 
      Date date = new Date(file.lastModified());
      System.out.println(date);
 
      try {
         String str = "01/31/1998";
         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
         Date newDate = sdf.parse(str);
         file.setLastModified(newDate.getTime());
      } catch(ParseException e) {
         System.out.println("ParseException");
      }
 
      date = new Date(file.lastModified());
      System.out.println(date);
 
   }
}

Output:
$ ls -l ChangeModificationTime.java 
-rw-rw-r-- 1 dennis dennis 664 Feb 26 12:44 ChangeModificationTime.java

$ java ChangeModificationTime
Thu Feb 26 12:44:31 EST 2015
Sat Jan 31 00:00:00 EST 1998

$ ls -l ChangeModificationTime.java 
-rw-rw-r-- 1 dennis dennis 664 Jan 31  1998 ChangeModificationTime.java

File to byte array in java

Question:
How do you write the contents of a file to a byte array in java?

Answer:
Files.readAllBytes(path);

Code:
import java.nio.file.*;
import java.io.*;
 
public class FileToArray {
  public static void main(String[] args) {
 
    byte[] bytes = null;
    try {
      Path path = Paths.get("file.txt");
      bytes = Files.readAllBytes(path);
    } catch (IOException e) {
    }
    for(int i: bytes) {
      System.out.print((char)i);
    }
 
  }
}

Output:
$ cat file.txt
This is the contents
of the file called 
file.txt

$ java FileToArray
This is the contents
of the file called 
file.txt

How to tell when a file was last modified?

Question:
How can you tell when a file was last updated in java?

Answer:
Use the File.lastModified() method.

Code:
import java.io.*;
import java.util.*;
 
public class FileModified {
   public static void main(String[] args) {
      File file = new File("FileModified.java");
      Date d = new Date(file.lastModified());
      System.out.println(d);
   }
}

Output:
$ java FileModified 
Fri Feb 28 06:59:28 EST 2014

$ ls -l FileModified.java 
-rw-r--r-- 1 dennis dennis 242 Feb 28 06:59 FileModified.java

How to get the size of a file?

Question:
How can you get the size of a given file in java?

Answer:
Use the method File.length().

Code:
import java.io.*;
 
public class FileSize {
   public static void main(String[] args) {
      File file = new File("FileSize.java");
      System.out.println("FileSize.java: "  + file.length());
   }
}

Output:
$ java FileSize 
FileSize.java: 201

$ ls -l FileSize.java
-rw-r--r-- 1 dennis dennis 201 Feb 28 06:51 FileSize.java

Counting words in a file.

Question:
How to count the number times a certain word appears in a file?

Answer:
Use the method Scanner.next() to read in each word of the file and then compare it with the desired word.

Code:
import java.io.*;
import java.util.*;
 
public class CountWords {
   public static void main(String[] args) {
 
      int count=0;
      String word = "cat";
 
      try {
         File file = new File("file.txt");
         Scanner sc = new Scanner(new FileInputStream(file));
 
         while(sc.hasNext()){
            if(word.equalsIgnoreCase(sc.next())){
               count = count + 1;
            }
         }
      } catch (Exception e) {
      }
      System.out.println("Number of " + word  + " words: " + count);
   }
}

Output:
$ cat file.txt 
Dog cat dog cat
Cat dog cat dog

$ java CountWords
Number of cat words: 4

Getting the first char of each line in a file.

Question:
How can I get the first character of each line in a file?

Answer:
See code.

Code:
import java.io.*;
 
public class ReadFile {
   public static void main(String[] args) {
      try {
         FileInputStream is = new FileInputStream("file.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String str;
         while ((str = br.readLine()) != null)   {
 
            char first = str.charAt(0);
            System.out.println(first);
 
         }
      } catch (Exception e) {
      }
   }
}

Output:
$ java ReadFile 
a
b
c
d

$ cat file.txt 
a bbb ccc ddd
bb ccc dddd eeee
cccc dd ee f
dd eeeeee fff ggg