Работа с файлами с
FileInputStream
и FileOutputStream
.
Читаю книгу Шилдта, дошёл до работы с файлами. В примере сказано что надо запускать программу из командной строки и вводить названия файлов. Но я учусь в IntelliJ. Как осуществить работу с файлами указав путь к ним?
Вот сам пример:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
public static void main(String[] args) {
int i;
FileInputStream fin;
FileOutputStream fout;
if (args.length != 2) {
System.out.println("Usage: CopyFile From To.");
return;
}
try {
fin = new FileInputStream(args[0]);
} catch (FileNotFoundException exc) {
System.out.println("Input file not found.");
return;
}
try {
fout = new FileOutputStream(args[1]);
} catch (FileNotFoundException exc) {
System.out.println("Error opening output file.");
try {
fin.close();
} catch (IOException exc2) {
System.out.println("Error closing input file.");
}
return;
}
try {
do {
i = fin.read();
if (i != -1) fout.write(i);
} while (i != -1);
} catch (IOException exc) {
System.out.println("Fi;e error.");
}
try {
fin.close();
} catch (IOException exc) {
System.out.println("Error closing input file.");
}
try {
fout.close();
} catch (IOException exc) {
System.out.println("Error closing output file.");
}
}
}
ПЕРЕЙДИТЕ В ПОЛНУЮ ВЕРСИЮ
В переменной сохраняем путь к файлу и потом прибавляем к arg[x] или пишем его полностью при вводе через коммандную строку.
В cmd/terminal надо будет писать что то вроде:
javac («путь к файлу») + CopyFile.java
java CopyFile a.txt b.txt
Если я не ошибаюсь…