-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyFile.java
More file actions
246 lines (227 loc) · 10.2 KB
/
MyFile.java
File metadata and controls
246 lines (227 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class MyFile {
public static void listDirectory(String path) {
File directoryPath = new File(path);
if (directoryPath.exists()) {
if (directoryPath.isDirectory()) {
String contents[] = directoryPath.list();
for (int i = 0; i < contents.length; i++) {
System.out.print(contents[i] + " ");
}
} else {
System.out.print("файл не может быть директорией");
}
} else {
System.out.print("директория отсутствует");
}
System.out.println();
}
public static void listPythonFiles(String path) {
File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
for (File filePy : file.listFiles()) {
if (filePy.getName().contains(".py")) {
System.out.print(filePy.getName() + " ");
}
}
} else {
System.out.print("файл не может быть директорией");
}
} else {
System.out.print("директория отсутствует");
}
System.out.println();
}
public static void isDirectory(String path) {
File pathIsDirectory = new File(path);
if (pathIsDirectory.exists()) {
System.out.println(pathIsDirectory.isDirectory());
} else {
System.out.println("директория отсутствует");
}
}
public static void define(String path) {
File pathIsDirectory = new File(path);
if (pathIsDirectory.exists()) {
if (pathIsDirectory.isDirectory()) {
System.out.println("директория");
} else {
System.out.println("файл");
}
} else {
System.out.println("директория или файл отсутствует");
}
}
public static void printPermissions(String path) {
File file = new File(path);
if (file.exists()) {
System.out.print(file.canRead() ? "r" : "-");
System.out.print(file.canWrite() ? "w" : "-");
System.out.print(file.canExecute() ? "x" : "-");
} else {
System.out.print("директория или файл отсутствует");
}
System.out.println();
}
public static void setPermissions(String path, String permissions) {
File file = new File(path);
if (file.exists()){
if (
(permissions.charAt(0) == 'r' || permissions.charAt(0) == '-') &&
(permissions.charAt(1) == 'w' || permissions.charAt(1) == '-') &&
(permissions.charAt(2) == 'x' || permissions.charAt(2) == '-')
) {
file.setReadable(false);
file.setWritable(false);
file.setExecutable(false);
file.setReadable(permissions.charAt(0) == 'r');
file.setWritable(permissions.charAt(1) == 'w');
file.setExecutable(permissions.charAt(2) == 'x');
}else {
System.out.println("""
Неверный Ввод
Для корректного ввода примеры ниже:
rwx : полный доступ Read Write Execute;
r-- : только Read;
-w- : только Write;
--x : только Execute;
--- : полный запрет Read Write Execute;
rw- , r-x итд.
""");
}
}else {
System.out.println("директория или файл отсутствует");
}
}
public static void printContent(String path) {
File file = new File(path);
try {
if (file.exists()){
if (!file.isDirectory()){
Scanner lines = new Scanner(file);
while (lines.hasNextLine()){
System.out.println(lines.nextLine());
}
}else {
System.out.println("каталог не может быть файлом");
}
}else {
System.out.println("директория или файл отсутствует");
}
}catch (Exception e){
System.out.println(e);
}
}
public static void appendFooter(String path) {
File file = new File(path);
if (file.exists()){
if (!file.isDirectory()){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file.getAbsolutePath(),true));
writer.append("# Autogenerated line");
writer.close();
}catch (Exception e){
System.out.println(e);
}
}else {
System.out.println("каталог не может быть файлом");
}
}else {
System.out.println("директория или файл отсутствует");
}
}
public static void createBackup(String path) {
File source = new File(path);
try {
if (source.exists()) {
java.time.LocalDate currentDate = java.time.LocalDate.now();
if (source.isDirectory()) {
File destination = new File("/tmp/" + currentDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + ".backup");
destination.mkdir();
copyDirectoryCompatibityMode(source, destination);
} else {
File destination = new File("/tmp/" + currentDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")) + ".backup");
destination.mkdir();
File destinationf = new File(destination, source.getName());
copyFile(source, destinationf);
}
} else {
System.out.println("директория или файл отсутствует");
}
} catch (Exception e) {
System.out.println(e);
}
}
private static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException {
if (!destinationDirectory.exists()) {
destinationDirectory.mkdir();
}
for (String f : sourceDirectory.list()) {
copyDirectoryCompatibityMode(new File(sourceDirectory, f), new File(destinationDirectory, f));
}
}
public static void copyDirectoryCompatibityMode(File source, File destination) throws IOException {
if (source.isDirectory()) {
copyDirectory(source, destination);
} else {
copyFile(source, destination);
}
}
private static void copyFile(File sourceFile, File destinationFile) throws IOException {
try (InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destinationFile)) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
}
public static void printLongestWord(String path) {
File file = new File(path);
if (file.exists()){
if (!file.isDirectory()){
try {
Scanner in = new Scanner(file);
String longestWord = "";
while (in.hasNextLine()){
for (String str:in.nextLine().replaceAll("[.:, /;]","\n").lines().toList()){
if (str.length()>longestWord.length()){
longestWord = str;
}
}
}
System.out.println(longestWord);
}catch (Exception e){
System.out.println(e);
}
}else {
System.out.println("каталог не может быть файлом");
}
}else {
System.out.println("директория или файл отсутствует");
}
}
public static void help() {
System.out.print("""
MyFS 1.0 команды:
ls <path> выводит список всех файлов и директорий для `path`
ls_py <path> выводит список файлов с расширением `.py` в `path`
is_dir <path> выводит `true`, если `path` это директория, в других случаях `false`
define <path> выводит `директория` или `файл` в зависимости от типа `path`
readmod <path> выводит права для файла в формате `rwx` для текущего пользователя
setmod <path> <perm> устанавливает права для файла `path`
cat <path> выводит контент файла
append <path> добавляет строку `# Autogenerated line` в конец `path`
bc <path> создает копию `path` в директорию `/tmp/${date}.backup` где, date - это дата в формате `dd-mm-yyyy`
greplong <path> выводит самое длинное слово в файле
help выводит список команд и их описание
exit завершает работу программы
""");
}
public static void exit() {
System.out.println("Goodbye");
}
}