We will read c:/myFile.txt
c:/myFile.txt looks like this >
abcdef
|
And output should be >
ef
|
Means skip 4 characters.
Logic>
We could achieve it by using skip method of FileInputStream. skip(n) method skips n number of bytes while reading the file. We can use skip(4) for skipping initial 4 characters.
Well the answer is size of char is 2 bytes in java means that character can occupy up to 2 bytes, but bytes occupied by character depends on platform default encoding.
- Some of character encoding like ISO-8859-1 generally occupies 1 byte for characters.
- Character Encoding like ASCII, UTF-8 or UTF-16 occupies variable-length like 1 byte for few characters while 2 bytes for others as well.
Program to Skip Characters while reading text from file using FileInputStream in java >
import java.io.FileInputStream;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class SkipCharactersUsingFileInputStream {
public static void main(String... args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("c:/myFile.txt");
fis.skip(4);
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close(); //close FileInputStream
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* OUTPUT
ef
*/
|
RELATED LINKS>
Read text from file using BufferedInputStream (and FileInputStream) in java file IO
Program to Read text from file in String using BufferedInputStream (and FileInputStream) in java file IO
Program to Read text from file using FileInputStream and Try with resource provided in java 7
Difference between loading file with FileInputStream and getResourceAsStream() in java
Labels:
Core Java
File IO/File handling