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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
|
package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// 1. 文件监控(简单实现)
func fileMonitoring() {
fmt.Println("=== 文件监控 ===")
monitorFile := "monitor_test.txt"
// 创建初始文件
err := os.WriteFile(monitorFile, []byte("初始内容\n"), 0644)
if err != nil {
log.Fatal("创建监控文件失败:", err)
}
defer os.Remove(monitorFile)
// 获取初始文件信息
initialInfo, err := os.Stat(monitorFile)
if err != nil {
log.Fatal("获取文件信息失败:", err)
}
fmt.Printf("开始监控文件: %s\n", monitorFile)
fmt.Printf("初始大小: %d 字节\n", initialInfo.Size())
fmt.Printf("初始修改时间: %v\n", initialInfo.ModTime())
// 启动监控goroutine
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
go func() {
lastModTime := initialInfo.ModTime()
lastSize := initialInfo.Size()
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
info, err := os.Stat(monitorFile)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("文件被删除")
return
}
continue
}
if info.ModTime() != lastModTime || info.Size() != lastSize {
fmt.Printf("文件变化检测到:\n")
fmt.Printf(" 大小: %d -> %d 字节\n", lastSize, info.Size())
fmt.Printf(" 修改时间: %v -> %v\n", lastModTime, info.ModTime())
lastModTime = info.ModTime()
lastSize = info.Size()
}
}
}
}()
// 模拟文件修改
time.Sleep(2 * time.Second)
file, _ := os.OpenFile(monitorFile, os.O_APPEND|os.O_WRONLY, 0644)
file.WriteString("添加的内容1\n")
file.Close()
time.Sleep(2 * time.Second)
file, _ = os.OpenFile(monitorFile, os.O_APPEND|os.O_WRONLY, 0644)
file.WriteString("添加的内容2\n")
file.Close()
time.Sleep(2 * time.Second)
fmt.Println("监控结束")
}
// 2. 大文件处理
func largeFileProcessing() {
fmt.Println("\n=== 大文件处理 ===")
largeFile := "large_file.txt"
// 创建大文件(模拟)
file, err := os.Create(largeFile)
if err != nil {
log.Fatal("创建大文件失败:", err)
}
defer file.Close()
defer os.Remove(largeFile)
// 写入大量数据
writer := bufio.NewWriter(file)
for i := 0; i < 100000; i++ {
line := fmt.Sprintf("这是第 %d 行数据,包含一些测试内容\n", i+1)
writer.WriteString(line)
}
writer.Flush()
file.Close()
// 获取文件大小
info, _ := os.Stat(largeFile)
fmt.Printf("大文件大小: %d 字节 (%.2f MB)\n",
info.Size(), float64(info.Size())/1024/1024)
// 分块读取大文件
file, err = os.Open(largeFile)
if err != nil {
log.Fatal("打开大文件失败:", err)
}
defer file.Close()
const chunkSize = 8192 // 8KB chunks
buffer := make([]byte, chunkSize)
var totalBytes int64
var chunkCount int
start := time.Now()
for {
n, err := file.Read(buffer)
if err == io.EOF {
break
}
if err != nil {
log.Fatal("读取文件失败:", err)
}
totalBytes += int64(n)
chunkCount++
// 处理数据块(这里只是计数)
if chunkCount%1000 == 0 {
fmt.Printf("已处理 %d 个数据块,%d 字节\n", chunkCount, totalBytes)
}
}
elapsed := time.Since(start)
fmt.Printf("处理完成: %d 个数据块,%d 字节,耗时: %v\n",
chunkCount, totalBytes, elapsed)
fmt.Printf("处理速度: %.2f MB/s\n",
float64(totalBytes)/1024/1024/elapsed.Seconds())
}
// 3. 并发文件处理
func concurrentFileProcessing() {
fmt.Println("\n=== 并发文件处理 ===")
// 创建多个测试文件
fileCount := 5
var files []string
for i := 0; i < fileCount; i++ {
fileName := fmt.Sprintf("concurrent_test_%d.txt", i)
content := fmt.Sprintf("这是文件 %d 的内容\n", i)
for j := 0; j < 1000; j++ {
content += fmt.Sprintf("行 %d: 一些测试数据\n", j)
}
err := os.WriteFile(fileName, []byte(content), 0644)
if err != nil {
log.Fatal("创建测试文件失败:", err)
}
files = append(files, fileName)
}
// 清理文件
defer func() {
for _, file := range files {
os.Remove(file)
}
}()
// 并发处理文件
var wg sync.WaitGroup
results := make(chan string, fileCount)
start := time.Now()
for _, fileName := range files {
wg.Add(1)
go func(file string) {
defer wg.Done()
// 处理文件(计算行数)
f, err := os.Open(file)
if err != nil {
results <- fmt.Sprintf("错误: %s - %v", file, err)
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
lineCount := 0
for scanner.Scan() {
lineCount++
}
results <- fmt.Sprintf("文件: %s, 行数: %d", file, lineCount)
}(fileName)
}
// 等待所有goroutine完成
go func() {
wg.Wait()
close(results)
}()
// 收集结果
for result := range results {
fmt.Println(result)
}
elapsed := time.Since(start)
fmt.Printf("并发处理 %d 个文件耗时: %v\n", fileCount, elapsed)
}
// 4. 文件搜索
func fileSearch() {
fmt.Println("\n=== 文件搜索 ===")
// 创建测试目录结构
testDir := "search_test"
os.MkdirAll(filepath.Join(testDir, "subdir1"), 0755)
os.MkdirAll(filepath.Join(testDir, "subdir2"), 0755)
defer os.RemoveAll(testDir)
// 创建测试文件
testFiles := map[string]string{
"file1.txt": "这个文件包含关键词 golang",
"file2.log": "日志文件内容",
"subdir1/config.json": `{"language": "golang", "version": "1.19"}`,
"subdir1/readme.md": "# Go项目\n这是一个golang项目",
"subdir2/data.csv": "name,language\nJohn,golang\nJane,python",
}
for filePath, content := range testFiles {
fullPath := filepath.Join(testDir, filePath)
os.WriteFile(fullPath, []byte(content), 0644)
}
// 搜索包含特定关键词的文件
keyword := "golang"
fmt.Printf("搜索包含关键词 '%s' 的文件:\n", keyword)
err := filepath.Walk(testDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
// 读取文件内容
content, err := os.ReadFile(path)
if err != nil {
return nil // 跳过无法读取的文件
}
// 检查是否包含关键词
if strings.Contains(strings.ToLower(string(content)),
strings.ToLower(keyword)) {
relPath, _ := filepath.Rel(testDir, path)
fmt.Printf(" 找到: %s\n", relPath)
// 显示包含关键词的行
lines := strings.Split(string(content), "\n")
for i, line := range lines {
if strings.Contains(strings.ToLower(line),
strings.ToLower(keyword)) {
fmt.Printf(" 第%d行: %s\n", i+1, strings.TrimSpace(line))
}
}
}
return nil
})
if err != nil {
log.Fatal("搜索失败:", err)
}
}
// 5. 文件备份
func fileBackup() {
fmt.Println("\n=== 文件备份 ===")
// 创建要备份的文件
originalFile := "backup_source.txt"
content := "这是要备份的重要文件内容\n包含多行数据\n需要定期备份"
err := os.WriteFile(originalFile, []byte(content), 0644)
if err != nil {
log.Fatal("创建源文件失败:", err)
}
defer os.Remove(originalFile)
// 创建备份目录
backupDir := "backups"
err = os.MkdirAll(backupDir, 0755)
if err != nil {
log.Fatal("创建备份目录失败:", err)
}
defer os.RemoveAll(backupDir)
// 创建带时间戳的备份
timestamp := time.Now().Format("20060102_150405")
backupFileName := fmt.Sprintf("backup_%s_%s", timestamp,
filepath.Base(originalFile))
backupPath := filepath.Join(backupDir, backupFileName)
// 复制文件到备份位置
src, err := os.Open(originalFile)
if err != nil {
log.Fatal("打开源文件失败:", err)
}
defer src.Close()
dst, err := os.Create(backupPath)
if err != nil {
log.Fatal("创建备份文件失败:", err)
}
defer dst.Close()
bytesWritten, err := io.Copy(dst, src)
if err != nil {
log.Fatal("备份文件失败:", err)
}
fmt.Printf("备份完成: %s\n", backupPath)
fmt.Printf("备份大小: %d 字节\n", bytesWritten)
// 验证备份
backupContent, err := os.ReadFile(backupPath)
if err != nil {
log.Fatal("读取备份文件失败:", err)
}
originalContent, err := os.ReadFile(originalFile)
if err != nil {
log.Fatal("读取原文件失败:", err)
}
if string(backupContent) == string(originalContent) {
fmt.Println("备份验证成功")
} else {
fmt.Println("备份验证失败")
}
}
func main() {
fileMonitoring()
largeFileProcessing()
concurrentFileProcessing()
fileSearch()
fileBackup()
}
|