Not getting file through FileInputStream?

I am trying to check the position of a file so that it is not overwritten. For this I have to use FileInputStream, because it has a method position()that can be used with FileChannel. BufferedReaderdoes not support the position.

My code is:

FileChannel fc = null;
FileInputStream fis = null;      
int i=0;
long pos;
char c;
fis = new FileInputStream("File.txt");
   while((i=fis.read())!=-1)
                         {
                            fc = fis.getChannel();
                            pos = fc.position();
                            c = (char)i;
                            System.out.print("No of bytes read: "+pos);
                            System.out.println("; Char read: "+c);
                         }

I get java.io.FileNotFoundException:

/doneQuestionDetail.txt: open failed: ENOENT (There is no such file or directory)

This error means that it does not receive the file from the location, because the file does not exist there, and if I use BufferedReader:

BufferedReader inputReader = new BufferedReader(
                                    new InputStreamReader(openFileInput("File.txt")));

There is no error on this line, which means that the file exists and FileInputStreamdoes not receive the file.

After searching, I need to get the location first, and then pass it FileInputStream, after which I changed the code, for example:

String extr = Environment.getExternalStorageDirectory().toString();
                            File mFolder = new File(extr + "/imotax");
                            String s = "doneQuestionDetail.txt";
                            File f = new File(mFolder.getAbsolutePath(), s);
                             fis = new FileInputStream(f);

:

java.io.FileNotFoundException:/mnt/sdcard/imotax/File.txt: failed: ENOENT ( )

. .

+4
1

.

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + File.separator
                        + "/imotax");
dir.mkdirs();
File f= new File(dir, fileToCreate);
if(!f.exists()){
f.createNewFile();
}

fis = new FileInputStream(f);
+1

Source: https://habr.com/ru/post/1570441/


All Articles