public class TxtInputStream extends FileInputStream {
String fileName;
public TxtInputStream(String fileName) throws Exception {
super(fileName);
// if filename is a correct string that leads to a txt file
// behave like a regular FileInputStream and read
// else throw UnsupportedFileNameException
// call super.close();
String[] sentences = fileName.split("\\.");
int length = sentences.length;
if (sentences[length-1].equals("txt")) {
FileInputStream fileInputStream = new FileInputStream(fileName);
} else {
super.close();
throw new UnsupportedFileNameException();
}
}
public static void main(String[] args) throws Exception {
TxtInputStream streamFile = new TxtInputStream("myFile.txt");
}
}
/*
We can use the split method from the String class to extract a substring. Say we want to extract the first sentence from the example String. This is quite easy to do using split:
String[] sentences = text.split("\\.");
Since the split method accepts a regex we had to escape the period character.
Then we take the last element of the array and make sure that that one is txt. The element index will be array length - 1. This way, even if name is "file.1231txt" or "file.txt.exe" we will always know if there is only txt at the end or not.
*/
Andrei
Level 41
Here is my solution, let me know what you think or if you have questions! :)
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
16 January 2021, 10:31
Great, another solved task :)
and in the meanwhile I believe split is coders darling (even if you won't need it here)
+1
Andrei
18 January 2021, 08:30
Cool, good to know! :)
0