"cannot find character" when trying to close I / O objects

public static int howMany(String FileName)
{
    BufferedReader br = null;

    try
    {
        FileInputStream fis = new FileInputStream(FileName);
        DataInputStream dis = new DataInputStream(fis);
        br = new BufferedReader(new InputStreamReader(dis));
    }
    catch (FileNotFoundException e)
    {
        System.out.print("FILE DOESN'T EXIST");
    }
    finally
    {
        fis.close();
        dis.close();
        br.close();
    }


    String input;
    int count = 0;

    try
    {

        while ((input = br.readLine()) != null)
        {
            count++;
        }

    }
    catch (IOException e) 
    {
        System.out.print("I/O STREAM EXCEPTION");
    }


    return count;
}

For some reason, I cannot close I / O objects. fis.close (), dis.close (), br.close () all let me not find the character, although I imported the entire I / O library (import java.io. *;) and triggered all the objects.

+5
source share
6 answers
 BufferedReader br = null;
 FileInputStream fis =null;
 DataInputStream dis null;
 try {
     fis = new FileInputStream(FileName);
     dis = new DataInputStream(fis);
     br = new BufferedReader(new InputStreamReader(dis));
 }

Put them out try blockso your finally block can see the variables.

+5
source

You must declare all threads outside the block try, otherwise they will not be visible in the block finally:

FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;

Alternatively, you can use Java 7's new try-with-resources syntax to automate resource closure.

+1
source

.

FileInputStream fis =null;
DataInputStream dis null;

-

try{

    fis = new FileInputStream(FileName);
    dis = new DataInputStream(fis);

   }
+1

fis try, . :

FileInputStream fis;
DataInputStream dis;
try
    {
        fis = new FileInputStream(FileName);
        dis = new DataInputStream(fis);
        br = new BufferedReader(new InputStreamReader(dis));
    }
0

:

BufferedReader br = null;
FileInputStream fis = null;
DataInputStream dis = null;
try
{
    fis = new FileInputStream(FileName);
    dis = new DataInputStream(fis);
    br = new BufferedReader(new InputStreamReader(dis));
}
0

, , finally, , . .

, BufferedReader . try .

, , . BufferedReader , , , , . , InputStreamReader , InputStream.

fis dis , :

br = new BufferedReader(new InputStreamReader(
        new DataInputStream(new FileInputStream(FileName))));

finally ; , .

, , finally, , try. ( , ) , , ( ), , .

try-with-resources, .

0

All Articles