1. How to append text into File in Java?
We can use FileWriter for appending string into file
2. How to read and write in text file in Java?
As a part of file read and write we should need to remember some points which should be taken care at the time of reading and writing to the file in Java.- Always try to use reference of abstract classes or interfaces in place of implemented class or we can say concrete class it is a one of the good java practice also.
- If needed use buffering it’s a good practice because calling a read() method for single byte JVM will call the native operating system method and calling a operating system method is expensive so Buffering will reduce this overhead from some extent.
- If using buffer then mentions the buffer size also it will affect the read time and CPU time also.
- Always Handle the Exceptions (IOException and FileNotFoundException)
- Don’t forget to call close() method for resource which we are using such as File or Directory in Java. You can also use automatic resource management in JDK7 to automatically close any open resource in Java.
3. How to Create File and Directory in Java Example?
Here is a simple example of how to create file in Java:
Just like above example of creating file in Java we can create directory in Java, only difference is that we need to use mkdir()
method to create directory in Java
4. How to read File into String in Java 7, 8 with Example?
This is how file reading happens on java 1.5 and 6
InputStream is = new FileInputStream("manifest.mf"); BufferedReader buf = new BufferedReader(new InputStreamReader(is)); String line = buf.readLine(); StringBuilder sb = new StringBuilder(); while(line != null){ sb.append(line).append("\n"); line = buf.readLine(); } String fileAsString = sb.toString(); System.out.println("Contents : " + fileAsString);
This is how file reading happens on JDK 1.7
String contents = new String(Files.readAllBytes(Paths.get("manifest.mf"))); System.out.println("Contents (Java 7) : " + contents);
But in java 8 its bit easy
Files.lines(Paths.get("manifest.mf"), StandardCharsets.UTF_8).forEach(System.out::println);
5. Difference between getPath(), getAbsolutePath() and getCanonicalPath() in Java?
Consider these filenames:
- C:\temp\file.txt - This is a path, an absolute path, and a canonical path.
- .\file.txt - This is a path. It's neither an absolute path nor a canonical path.
- C:\temp\myapp\bin\..\\..\file.txt - This is a path and an absolute path. It's not a canonical path.
A canonical path is always an absolute path.
Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt becomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\ and resolving symlinks (on unixes).
Also note the following example with nio.Paths:
String canonical_path_string = "C:\\Windows\\System32\\"; String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\"; System.out.println(Paths.get(canonical_path_string).getParent()); System.out.println(Paths.get(absolute_path_string).getParent());
While both paths refer to the same location, the output will be quite different:
C:\Windows C:\Windows\System32\drivers
6. Difference between Direct, Non Direct and Mapped ByteBuffer in Java?
ByteBuffer is one of the important class of Java NIO API. It was introduced in java.nio package on JDK 1.4, it not only allows you to operate on heap byte arrays but also with direct memory, which resides outside the JVM.
- The first difference between non-direct and direct byte buffer comes from the fact, how you create them. You can create non-direct byte buffer either by allocating space for buffer's content or by wrapping an existing byte array into a buffer. While a Direct byte buffer may be created by calling factory method allocateDirect() or by mapping a region of a file directly into memory , known as MappedByteBuffer.
- In the case of Direct byte buffer, JVM performs native IO operation directly into the buffer, without copying them into any intermediate buffer, this makes it very attractive for performing high-speed IO operation on them, but this facility comes with care. If a memory mapped file is shared between multiple processes then you need to ensure that it won't get corrupted i.e. some regions of memory mapped file not becoming unavailable.
- One more difference between direct and non-direct byte buffers are that former's memory footprint may not be obvious because they are allocated outside of Java heap while non-direct buffers consume heap space and are subject to garbage collection.
- You can check whether a byte buffer is direct or non-direct by calling isDirect() method from java.nio.ByteBuffer class. It returns true if byte buffer is direct.
7. Different ways to convert InputStream to String in Java?
1. InputStream to String - Using Java 5 Scanner
2. Convert InputStream to String - Plain old JDK4 Example
3. Read InputStream to String - Using Apache IOUtils library
/** * Example of How to read InputStream into String by using Apache IOUtils library. * Nice and clean way of getting InputStream as String in Java */ FileInputStream fis = new FileInputStream("c:/sample.txt"); String StringFromInputStream = IOUtils.toString(fis, "UTF-8"); System.out.println(StringFromInputStream);
4. InputStream to String - Using Google's guava-libraries
5.How to read InputStream into String with IOUtils.copy and StringWriter class
8. How to read file line by line in Java?
Reading file line by line in Java - BufferedReader Example
Reading file line by line in Java - Scanner Example
9. different ways to Parse CSV Files in Java?
2 ways to read CSV files in Java. First way is by using java.io.BufferedReader and split() method from java.lang.String class, and second way is by using Apache Commons CSV library's CSVParser class. Commons CSV is new member in rich Apache commons family and has built in support to read most common CSV formats e.g. RFC 4180, Microsoft Excel, MySQL and TDF.
10. How to read Zip Files in Java?
There are two ways you can iterate over all items in a given zip archive, you can use either java.util.zip.ZipFile or java.util.zip.ZipInputStream. Since a Zip file contains several items, each of them has header field containing size of items in number of bytes. Which means you can iterate all entries without actually decompressing the zip file.
You can ask ZipFile for InputStream corresponding to this file entry for extracting real data. Which means, you only incur cost of decompression, when you really need to. By using java.util.zip.ZipFile, you can check each of entry and only extract certain entries, depending upon your logic.
ZipFile is good for both sequential and random access of individual file entries. On the other hand, if you are using ZipInptStream then like any other InputStream,
11. How to Copy File in Java Program?
Below is the complete code example of copying one file in Java. We need to provide absolute path of source file to copy and destination directory. you can get the name of file by calling File.getName() and FileUtils will create the same file in destination directory with same name.
12. How to Convert Byte Array to InputStream and OutputStream in Java?
13. How to Convert InputStream to Byte Array in Java?
14. Difference between FileInputStream and FileReader in Java?
FileReader extends InputStreamReader, it uses character encoding provided to this class, or else default character encoding of platform. Remember, InputStreamReader caches the character encoding and setting character encoding after creating object will not have any affect. Let's see an example of How to use FileInputStream and FileReader in Java. You can provide either a File object or a String, containing location of file to start reading character data from File. This is similar to FileInputStream, which also provides similar constructors for reading from file source.
15. How to find current directory in Java ?
16. How to delete a directory with files in Java?
Primary method to delete a file or directory in Java was File.delete() method form java.io package. This method can be used to delete a file or a nonempty directory but fail silently when it comes to deleting folder with files. If you ignore return value of this method, which is false if it failed to delete directory then you will never know that whether your program failed to remove some directory and I have seen many developers hit by this bullet. Thankfully, JDK 7 added another delete()
method in Files utility class to delete file and directory, which throws IOException when a file cannot be deleted. This is really useful for troubleshooting purpose e.g. to find out why a file cannot be deleted. There is one more similar method, Files.deleteIfExists(), which is slightly more readable than original delete()
method from File class.
17. How to Read File in One Line in JDK 7 or Java 8?
18. How to create hidden file in Java?
Hide a File in Java5 with Example
void setHiddenProperty(File file) throws InterruptedException, IOException { Process p = Runtime.getRuntime().exec("attrib +H " + file.getPath()); p.waitFor(); }
Code Example of making a file hidden in JDK7
Path path = FileSystems.getDefault().getPath("directory", "hidden.txt"); Boolean hidden = path.getAttribute("dos:hidden", LinkOption.NOFOLLOW_LINKS); if (hidden != null && !hidden) { path.setAttribute("dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); }
No comments:
Post a Comment