Если обернуть попытку обращения к файлу в блок try
try{
String sourceFileName = reader.readLine();
InputStream fileInputStream = getInputStream(sourceFileName);
}
то потом в цикле while, во время уже чтения данных из файла, вот тут
while (fileInputStream.available() > 0)
переменная потока уже не видна, она не объявлена, и поэтому программа не компилируется.
А если добавить объявление и инициализацию вне блоков try и catch
InputStream fileInputStream = null;
то компилятор уже ругается на то, что переменная уже инициализирована в блоках try и catch.
Error:(15, 25) java: variable fileInputStream is already defined in method main(java.lang.String[])
Error:(20, 25) java: variable fileInputStream is already defined in method main(java.lang.String[])
package com.javarush.task.task09.task0929;
import java.io.*;
/*
Обогатим код функциональностью!
*/
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
InputStream fileInputStream = null;
try {
String sourceFileName = reader.readLine();
InputStream fileInputStream = getInputStream(sourceFileName);
}
catch (IOException e){
System.out.println("Файл не существует");
String sourceFileName = reader.readLine();
InputStream fileInputStream = getInputStream(sourceFileName);
}
String destinationFileName = reader.readLine();
OutputStream fileOutputStream = getOutputStream(destinationFileName);
while (fileInputStream.available() > 0) {
int data = fileInputStream.read();
fileOutputStream.write(data);
}
fileInputStream.close();
fileOutputStream.close();
}
public static InputStream getInputStream(String fileName) throws IOException {
return new FileInputStream(fileName);
}
public static OutputStream getOutputStream(String fileName) throws IOException {
return new FileOutputStream(fileName);
}
}