이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

파일찾기

A라는 디렉토리 하위에 있는 텍스트 파일(*.txt) 중에서 LIFE IS TOO SHORT 라는 문자열을 포함하고 있는 파일들을 모두 찾을 수 있는 프로그램을 작성하시오.

단, 하위 디렉토리도 포함해서 검색해야 함.

재귀호출

2014/02/26 22:33

pahkey

81개의 풀이가 있습니다.

프로그램은 아니지만 유용한 유닉스 명령어입니다.

$ cd A
$ find ./ -name *.txt |xargs grep "LIFE IS TOO SHORT"

2014/02/27 23:20

pahkey

python 입니다. 문제풀이를 통해 os.walk() 을 배웠네요 ^^

import os

def func(dirname):
  for root, dirs, files in os.walk(dirname):
    for name in files:
      if '.txt' in name: 
        f = open(os.path.join(root,name),'r')
        txt = f.read()
        if 'LIFE IS TOO SHORT' in txt: print name
        f.close()

func('.')

2015/01/08 12:35

Sang Brian

배워갑니다~ - Taesoo Kim, 2018/06/04 15:17
os.walk 사용법 알게되었습니다. - 약사의혼자말, 2021/05/25 16:33

Ruby.

Dir.glob("**/*.txt").select{|i| File.read(i) =~ /LIFE IS TOO SHORT/}

2014/02/28 03:56

nacyot

와우, 정말 직관적이네요, perl처럼 유닉스 커맨드라인 명령어로도 가능하다면 활용도가 무척 높을것 같습니다. - pahkey, 2014/02/28 10:06
+3 커맨드라인에선 ruby -e 'Dir.glob("**/*.txt").select{|i| File.read(i) =~ /LIFE IS TOO SHORT/}' 이렇게 합니다 >_< - nacyot, 2014/03/02 12:18
Python 몇달 배우고 있는 초보자인데... Ruby 멋지네요.. - 로만가, 2022/02/07 19:26

Clojure 코드입니다. file-seq 함수가 지정한 위치의 파일/디렉토리들을 재귀적으로 탐색해줍니다.

(fn [A]
  (filter #(and (.isFile %)
                (re-find #"\.txt$" (.getName %))
                (re-find #"LIFE IS TOO SHORT" (slurp %)))
          (file-seq (clojure.java.io/file A))))

2014/02/27 00:35

박연오

자바로 짜봤어요.. 하다보니 뭔가 길게 짠거 같은데..ㅋ역시 최적화는 어렵네요.

import java.io.*;

public class File_Search {

    public static String currDir = null;

    public static void main(String[] args) {
        currDir = System.getProperty("user.dir");       
        find(currDir);
    }

    public static void find(String filename) {
        File f = new File(filename);
        if (f.isDirectory()) {
            System.out.println("Entering into Directory : " + filename);

            String path = f.getAbsolutePath();
            String[] lists = f.list();

            for (int i=0; i < lists.length; i++) {
                find(path + "\\" + lists[i]);
            }

        } else if (f.toString().endsWith(".txt")) {         
            String line = null;
            try {
                BufferedReader readFile = new BufferedReader(new FileReader(filename));
                while ((line = readFile.readLine()) != null) {
                    if (line.matches(".*LIFE IS TOO SHORT.*")) {
                        System.out.println("found in " + filename);
                        break;
                    }
                }               
                readFile.close();
            } catch (Exception e) {
                System.out.println("can't open a file : " + e.getMessage());
            }   
        }
    }
}

2014/02/27 14:10

[email protected]

import os
import re

_filelist=[]
for cur, _dirs, files in os.walk('c:\\A'):
    for filenm in files:
        if re.search('.*\.txt',filenm):
            with open(cur+"\\"+filenm,'r') as f:
                for line in f:
                    if  re.search("LIFE IS TOO SHORT",line):
                        _filelist.append(cur+"\\"+filenm)

print(_filelist)

파이썬 초보입니다. for문이 많아서 가독성은 좀 떨어지네요^^ 파이썬이라면 아마 더좋은 방법이 있을거라고 생각합니다.

2014/03/03 15:54

무명소졸

import glob2
list(filter(lambda x: "LIFE IS TOO SHORT" in open(x).read(), glob2.glob("A/**/*.txt")))

파이썬으로 만들어 보았습니다.

기본으로 들어있는 glob를 사용했더니 디렉토리 재귀가 안되어서 glob2를 pip로 받아서 사용하였습니다.

2014/10/31 14:23

꿍스군

import os

def find(text, ext='.txt'):
    result = []
    for files in os.walk('.'):
        for file in files[2]:
            if file.endswith(ext):
                with open(os.path.join(files[0], file),'r') as f:
                    if text in f.read():
                        result.append(os.path.join(files[0], file))
    return result


그냥 grep 쓰는게.....

2014/12/11 17:51

룰루랄라

fish 입니다.

grep -l "LIFE IS TOO SHORT" **.txt

zsh에서는 약간 길어집니다.

grep -l "LIFE IS TOO SHORT" **/*.txt

2015/01/13 16:20

Shim Won

coding by python beginner

import sys, os

t0 = os.popen( 'find ' + sys.argv[1] + ' -name "*.txt"' )
files = []
for file in t0.read().split('\n'):
    if file:
        f = open(file, 'r');
        t0 = f.read()
        if t0.find('LIFE IS TOO SHORT') != -1: files.append(file)
        f.close()

print(files)

2015/01/23 22:24

vegan

펄입니다

use latest;
use File::Spec;
sub bfs{
    my $path=$_[0];
    my($current,@output);
    push(my @queue,$path);
    while(@queue){
        $path=shift(@queue);
        if($path=~/\/\.{1,2}$/){next}
        if(-d $path){
            opendir($current,$path);
            push @queue,map {File::Spec->catfile($path,$_)} readdir $current;
            closedir $current
        }
        elsif(-f $path and $path=~/\.txt$/){
             open($current,$path);
             push @output,$path if grep(/LIFE IS TOO SHORT/,<$current>);
             close($current)
        }
    }
    @output;
}
say bfs($ARGV[0]);

2015/01/24 05:11

이병곤

grep -r 'LIFE IS TOO SHORT

2015/01/25 03:06

jabber24

Using python 뭔가 다른 분들과...똑같은....ㅠㅠ

import os

def fSearch(origin):
    for path, dirs, file_name in os.walk(origin):
        for files in file_name:
            if os.path.splitext(files)[-1] == ".txt":
                f = open(os.path.join(path,files)).read()
                if f.find("LIFE IS TOO SHORT") > -1:
                    print files

fSearch("C:\")

2015/03/31 16:30

freeefly

import os

#데이터
string = "LIFE IS TOO SHORT"

#처리
def func(dirname):
  for root, dirs, files in os.walk(dirname):
    for name in files:
      if ".txt" in name: 함
        f = open(os.path.join(root,name), "r")
        txt = f.read()
        if string in txt:
            print(name)
        f.close()


#입출력
func(".") 

2015/04/04 02:04

zerofury

    Sub main()
        Dim fs() As IO.FileInfo = New IO.DirectoryInfo("Path").GetFiles("*.txt", IO.SearchOption.AllDirectories)

        For Each f As IO.FileInfo In fs
            If My.Computer.FileSystem.ReadAllText(f.FullName).Contains("LIFE IS TOO SHORT") Then
                Console.WriteLine(f.FullName)
            End If
        Next

        Console.ReadLine()
    End Sub

2015/06/13 01:10

Steal

쉘 스크립트입니다. find + xargs grep은 자주 쓰는 명령이지요..

#!/bin/bash

dir="."

if [ $# -gt 0 ]
then
        dir=$1
fi

find $dir -name "*.txt" | xargs grep "LIFE IS TOO SHORT" 2> /dev/null

2015/11/26 11:09

jspark

파이썬 2.7


import os

dirname = '.'

for (path, dir, files) in os.walk(dirname):
    for filename in files:
        if '.txt' in filename:
            with open(os.path.join(path, filename)) as f:
                text = f.read()
                if 'LIFE IS TOO SHORT' in text:
                   print os.path.abspath(path) + filename

2015/12/31 11:06

hana11

import os

def find(path = '경로'):
    for (path, dirs, files) in os.walk(path):
        for file in files:
            if os.path.splitext(file)[-1] == '.txt':
                if 'LIFE IS TOO SHORT' in open(os.path.join(path,file), 'r').readline():print(path, file)

if __name__ == '__main__':
    find()

os 모듈은 처음 써보네요... 파이썬 3.5.1입니다.

2016/03/13 19:23

Flair Sizz

C#으로 작성했습니다.

using System.Collections.Generic;
using System.IO;
using System.Linq;

        public static List<string> GetFileDirectories(string input)
        {
            var subDirectories = Directory.GetDirectories(input, "*", SearchOption.AllDirectories);
            var outputs = new List<string>();
            foreach (var directory in from subDirectory in subDirectories select subDirectory)
                foreach (var file in new DirectoryInfo(directory).GetFiles("*.txt"))
                    if (File.ReadAllText(file.FullName).Contains("LIFE IS TOO SHORT")) 
                        outputs.Add(file.FullName);
            foreach (var file in new DirectoryInfo(input).GetFiles("*.txt"))
                if (File.ReadAllText(file.FullName).Contains("LIFE IS TOO SHORT")) outputs.Add(file.FullName);
            return outputs;
        }

2016/04/12 10:04

Straß Böhm Jäger

Python 3.4

import os

def find_context_in_file(dir):
    for root, dirs, files in os.walk(str(dir)):
        for file in files:
            try:
                with open(file) as f:
                    if f.read().find("LIFE IS TOO SHORT"):
                        print(os.path.abspath(file))
            except IOError as error:
                pass
        find_context_in_file(dirs)

find_context_in_file("./")

2016/05/04 12:40

SanghoSeo

Ruby

ls = ->ext,str { Dir.glob("**/*.#{ext}").select {|f| File.read(f)=~/#{str}/ } }

Test

expect(ls["txt","LIFE IS TOO SHORT"]).to eq []
expect(ls["rb","crawl"]).to eq ["lib/random_walk.rb", "spec/coding_dojang_spec.rb"]

Output

#=>puts ls["txt","LIFE IS TOO SHORT"]

#=>puts ls["rb","crawl"]
lib/random_walk.rb
spec/coding_dojang_spec.rb

2016/05/04 15:31

rk

Python 3로 작성하였습니다. 파일을 열때 인코딩 문제가 있어 이부분까지 고려하여 작성하였습니다.

import os
import glob
import sys

def findFile(dirname = "."):
    for filename in glob.glob(os.path.join(dirname, "**/*.txt"), recursive=True):
        for encoding in ("UTF-8", "UTF-16", "euc-kr", "ascii"):
            try:
                with open(filename, "r", encoding=encoding) as f:
                    lines = f.read()
                    if 'LIFE IS TOO SHORT' in lines:
                        print(filename)
                    break
            except:
                pass

# Test
if __name__ == "__main__":
    findFile(sys.argv[1])
결과
$> python FindFile.py .
..\FindFile\FindFile.txt

2016/09/28 18:06

윤태호

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class FileSerch {

    public static void main(String[] args) {
        ArrayList<File> txtFiles = new ArrayList<File>();
        String path = "C:/Users/woo/Desktop/A";

        Serch(path);

    }

    public static void Serch(String path) {
        File f = new File(path);

        if (!f.exists()) {
            System.out.println("존재하지 않는 디렉토리 입니다.");
            return;
        }

        File[] allFiles = f.listFiles();
        for (File file : allFiles) {
            if (file.getName().endsWith(".txt")) {

                try {
                    BufferedReader in = new BufferedReader(new FileReader(file));
                    String s;
                    while ((s = in.readLine()) != null) {
                        if(s.contains("LIFE IS TOO SHORT")) {
                            System.out.println(file.getName()+ "  "+s);
                        }
                    //in.close();
                    }
                } catch (IOException e) {
                    System.err.println(e); 
                    System.exit(1);
                }


            } else if (file.isDirectory()) {
                path = path + "/" + file.getName();
                System.out.println(path);
                Serch(path);
            }
        }
    }
}

2016/10/05 15:58

코딩초보

Haskell로 작성하였습니다.

import System.Directory
import System.FilePath.Posix
import Control.Monad
import Data.List

-- check isInfixOf "LIFE IS TOO SHORT"
isInfixOfText filename = do
    contents <- readFile filename
    if isInfixOf "LIFE IS TOO SHORT" contents
        then print filename
        else return ()

-- recursive search file function
searchDir curDir = do
    contents <- getDirectoryContents curDir
    forM_ [x | x <- contents, not (elem x [".", ".."])] (\content -> do
        let curContent = joinPath [curDir, content]
        isDir <- doesDirectoryExist curContent
        if isDir
            then searchDir curContent
            else isInfixOfText curContent
        )

-- run from current directory
main = searchDir "."

2016/10/27 02:13

윤태호

Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class CheckFile {
    public static void main(String[] args) throws IOException {
        Predicate<Path> checkFile = p -> {
            try (Stream<String> stream = Files.lines(p)) {
                return stream.anyMatch(line -> line.toUpperCase().contains("LIFE IS TOO SHORT"));
            } catch (IOException ioe) {
                return false;
            }
        };
        Path path = Paths.get("A");
        Files.walk(path)
                .filter(p -> p.toString().toLowerCase().endsWith(".txt"))
                .filter(checkFile)
                .forEach(System.out::println);
    }
}

2016/10/27 11:36

compert

다른 언어들도 그냥 라이브러리 이용하는 분위기니.. Haskell도 그냥.. ;-)

{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString as BS
import Control.Monad
import System.FilePath.Glob -- "glob"

contains fp a = BS.isInfixOf a <$> BS.readFile fp
main = glob "**/*.txt" >>= filterM (`contains` "LIFE IS TOO SHORT") >>= print

(문제 의도는 '재귀호출'인데 말이죠 ㅎㅎ)

2016/11/15 00:40

Han Jooyung

import os
import re
def search_dir(path, pattern):
    results = []
    try:
        files = os.listdir(path)
        for file in files:
            fullpath = os.path.join(path, file)
            if os.path.isdir(fullpath):
                results += search_dir(fullpath, pattern)
            else:
                if pattern(fullpath):
                    results.append(fullpath)
    except:
        pass
    return results

pattern_txt = re.compile(r'\.txt$', re.I)
pattern_str = re.compile(r'LIFE IS TOO SHORT')
def pattern_list_is_too_short(path):
    if not pattern_txt.search(path):
        return False
    try:
        with open(path, 'r') as f:
            if pattern_str.search(f.read()):
                return True
    except:
        pass
    return False

path=input('path:')
print('검색된 파일:')
for l in search_dir(path, pattern_list_is_too_short):
    print(l)

Python 3.5.2에서 작성하였습니다.

2016/11/28 09:58

Yeo HyungGoo

import os

for path,dirs,files in os.walk('C:\\Python34\\A'):
    for file in files:
        if file[-4:] == '.txt':
            fd = open(os.path.join(path,file),'r')
            string = fd.read()
            if 'LIFE IS TOO SHORT' in string:
                print(file)
            fd.close()

#### 2016.12.22 D-427 ####

크하 하나배우기 힘듭니다!ㅎㅎ

2016/12/22 23:18

GunBang

파이썬 3.x 기준으로 작성하였습니다.

# -*- coding: utf-8 -*- 
import os
dirname = "C:/" # 경로
msg = "LIFE IS TOO SHORT"
def find(path = dirname):
    for (path, dirs, files) in os.walk(path):
        for file in files:
            if os.path.splitext(file)[-1] == '.txt':
                if msg in open(os.path.join(path,file), 'r').readline():
                    print(path, file)

if __name__ == '__main__':
    find()

2017/01/01 19:56

주 현태

Python 3.4.2, tag 가 '재귀호출'이네요. os.walk 를 사용했는데...

import os, sys

def text_search(rootdir, findtext):
    for (dirpath, dirnames, filenames) in os.walk(rootdir):
        for filename in filenames:
            ext = os.path.splitext(filename)[-1]
            if ext == '.txt':
                text_path = os.path.join(dirpath, filename)
                if findtext in open(text_path).read():
                    print(text_path)

실행결과

>>> text_search('/home/pi', 'LIFE IS TOO SHORT')
/home/pi/test2.txt
/home/pi/example/test1.txt
/home/pi/subdir/test2.txt

2017/05/18 03:20

예강효빠

파이썬 3으로 클래스 연습하여서 작성해보았습니다.

import os

class fileSearching:
    searchSen = '';
    def __init__(self, searchSen):
        self.searchSen = searchSen
    def printSearchSen(self):
        print (self.searchSen)
    def searchFiles(self, currentPath):
        for fileName in os.listdir(currentPath):
            fileNameAndPath = currentPath + "/" + fileName
            if os.path.isdir(fileNameAndPath):
                self.searchFiles(fileNameAndPath)
            else:
                if self.searchSen in open(fileNameAndPath).read():
                    print (fileNameAndPath)

if __name__ == "__main__":
    fileSearch = fileSearching("LIFE IS TOO SHORT")
    fileSearch.printSearchSen()
    fileSearch.searchFiles(".")

2017/05/27 10:20

Mike

import os

def find_text(filename,sentence):
    f=open(filename,'r')
    while True:
        line=f.readline()
        if not line:
            break
        if line == sentence:
           print(filename,line)
    f.close()
def find_file(dirname):
    for (path, dir, files) in os.walk(dirname):
        for filename in files:
            ext = os.path.splitext(filename)[-1]
            if ext == '.txt':
                string=path+"/"+filename
                find_text(string,find_want_txt)

find_want_txt="LIFE IS TOO SHORT"
dirname="C:/test"
find_file(dirname)

2017/06/13 12:14

나후승

from pathlib import Path


def txt_rscan(dirpath, targettxt):
    for txtfile in Path(dirpath).rglob('*.txt'):
        try:
            if targettxt.upper() in txtfile.read_text().upper():
                print(txtfile)
        except:
            print('Error reading file:', txtfile)

2017/07/05 05:45

Noname

[Python 3.6]

import os
def findFileList(directiroy):
    foundList = []
    for (path, dirs, filenames) in os.walk(directiroy):
        for filename in (file for file in filenames if os.path.splitext(file)[-1] == ".txt"):
            fullFilename = os.path.join(path, filename)
            with open(fullFilename) as f:
                try:
                    if "LIFE IS TOO SHORT" in f.read(): foundList.append(fullFilename)
                except: continue
    return foundList

2017/07/22 13:23

Eliya

import os

def f(dir1):
    arr1 = []
    for (path, dir, files) in os.walk(dir1):
        for filename in files:
            if filename.split('.')[-1] == 'txt':
                f1 = open(os.path.join(path, filename), 'r')
                f2 = f1.read().replace('\n','')
                if f2.count('LIFE IS TOO SHORT') > 0:
                    arr1.append(os.path.join(path, filename))
                f1.close()
    print(arr1)

f('D:\\')

2017/08/31 11:11

piko

import os

for (path, dir, files) in os.walk("c:/"):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        full_filename = "%s/%s" % (path, filename)
        if ext == '.txt':
            f = open(full_filename, 'r')
            line = f.readline()
            if 'LIFE IS TOO SHORT' in line:
                print(full_filename)
            f.close()

2017/09/04 15:59

검은콩

# python 3.6
import os

A = "d:/temp"  # starting derectory


def chk_str(filename: str, string: str)->bool:
    """filename 내에 string이 존재하는지 판별하여 부울 갑 반환"""
    with open(filename, "r") as f:
        return string in f.read()


rst = list()  # 조건에 만족하는 파일명(경로포함)이 저장됨
for (path, __, files) in os.walk(A):
    lst = [path + "\\" + file for file in files if os.path.splitext(
        file)[-1].lower() == ".txt"]  # 확장자 조건 검색
    for full_path_file in lst:
        if chk_str(full_path_file, "LIFE IS TOO SHORT"):  # 문자열 조건 검색
            rst.append(full_path_file)

print(rst)

2017/09/26 10:07

mohenjo

파이썬 3.6

import os

currentdir = os.getcwd()

def searchdir(currentdir):
    filenames = os.listdir(currentdir)
    for filename in filenames:
        full_filename =''
        full_filename = os.path.join(currentdir,filename)
        if os.path.isdir(full_filename):
            searchdir(full_filename)
        else:
            ext = os.path.splitext(full_filename)[-1]
            if ext == '.txt':
                f = open(full_filename ,'r')
                if 'LIFE IS TOO SHORT' in text:
                    print(full_filename)
                f.close()

searchdir(currentdir)

2018/01/02 16:31

justbegin

# 파이썬
# os.walk(top, topdown=True, onerror=None, followlinks=False)

import os


def str_finder(dirname, str1):
    for root, dirs, files in os.walk(dirname):
        for name in files:
            if '.txt' in name:
                t = open(os.path.join(root, name), 'r')\
                text = t.read()
                if str1 in text:
                    print(name)
                t.close()


sample_dir = "c:\ "
str_finder(sample_dir, 'LIFE IS TOO SHORT')


2018/02/05 14:02

olclocr

import os


def searchtxt(str,bstr):
    result = list()
    for (path, dir, files) in os.walk(str):
        try:
            for filename in files:
                ext = os.path.splitext(filename)[-1]
                if ext == '.txt':
                    f = open(os.path.join(path,filename),'rb')
                    data = f.read()
                    f.close()
                    if bstr in data:
                        result.append(os.path.join(path,filename))
        except PermissionError:
            pass
    return result


print(searchtxt("C:/",b'LIFE IS TOO SHORT'))

2018/02/07 01:06

김동하

import os

def check_txt(filename):
    f=open(filename,'r')
    data=f.read()
    if "LIFE IS TOO SHORT" in data:
        return True
    else:
        return False
    f.close()





def search(dirname):
    try:
        filenames=os.listdir(dirname)
        for filename in filenames:
            full_filename=os.path.join(dirname,filename)
            if os.path.isdir(full_filename):
                search(full_filename)
            else:
                ext=os.path.splitext(full_filename)[-1]
                if ext==".txt":
                    if check_txt(full_filename)==True:
                        print(full_filename)
    except PermissionError:
        pass



directory=input("디렉토리를 입력하세요\n")
search(directory)

2018/02/17 21:46

D B

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileFinder {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String filePath = "C:\\Users\\present\\Desktop\\test";

        File file = new File(filePath);

        if(file.isDirectory()){

            for(String str : file.list()){
                File file2 = new File(filePath + "\\" + str);
                Scanner sc;
                try {
                    sc = new Scanner(file2);
                    while(sc.hasNextLine()){
                        String line = sc.nextLine();
                        if(line.contains("LIFE IS TOO SHORT")){
                            System.out.println(str);
                            break;
                        }
                    }
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }else{
            System.out.println("디렉토리가 아닙니다.");
        }
    }

}

2018/03/16 21:36

김태훈

/* 파일찾기 */
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "strings"
)

func main() {
    rootpath := "C:/MyApp"
    ext := ".txt"
    chkString := "LIFE IS TOO SHORT"

    for _, v := range Search(rootpath, ext, chkString) {
        fmt.Println(v)
    }
}

func Search(rootpath, ext, chkString string) []string {
    rst := []string{}
    pool, ok := getFileList(rootpath, ext)
    if !ok {
        fmt.Println("Not found any file with ext: ", ext)
        os.Exit(0)
    }
    for _, v := range pool {
        if chkFile(v, chkString) {
            rst = append(rst, v)
        }
    }
    if len(rst) == 0 {
        rst = append(rst, "No such file.")
    }
    return rst
}

// chkFile: filename 파일 내의 chkString 존재여부 반환
func chkFile(filename, chkString string) bool {
    bs, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Printf("check file error: [%v]\n", err)
        os.Exit(0)
    }
    str := string(bs)
    return strings.Contains(str, chkString)
}

// getFileList: ext 확장자를 가진 파일의 슬라이스 및 존재여부 반환
func getFileList(rootpath, ext string) ([]string, bool) {
    list := []string{}
    rst := filepath.Walk(rootpath, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if strings.ToLower(filepath.Ext(path)) == ext {
            list = append(list, path)
        }
        return nil
    })
    if rst != nil {
        fmt.Printf("File walk error: [%v]\n", rst)
        os.Exit(0)
    }
    ok := true
    if len(list) == 0 {
        ok = false // 확장자의 파일이 존재하지 않을 경우
    }
    return list, ok
}

2018/03/27 12:41

mohenjo

def find1(dirname):
    import os
    for path, dirs, file_name in os.walk(dirname):
        for name in file_name :
            if '.txt' in name :
                f = open(os.path.join(path,name),'r')
                txt = f.read()
                if 'HELLO' in txt : print(os.path.join(path,name))
                f.close()


find1("D:/TEST/")

2018/03/30 17:52

yijeong

import java.io.*;

public class File_Search {

    public static String currDir = null;

    public static void main(String[] args) {
        currDir = System.getProperty("user.dir");       
        find(currDir);
    }

    public static void find(String filename) {
        File f = new File(filename);
        if (f.isDirectory()) {
            System.out.println("Entering into Directory : " + filename);

            String path = f.getAbsolutePath();
            String[] lists = f.list();

            for (int i=0; i < lists.length; i++) {
                find(path + "\\" + lists[i]);
            }

        } else if (f.toString().endsWith(".txt")) {         
            String line = null;
            try {
                BufferedReader readFile = new BufferedReader(new FileReader(filename));
                while ((line = readFile.readLine()) != null) {
                    if (line.matches(".*LIFE IS TOO SHORT.*")) {
                        System.out.println("found in " + filename);
                        break;
                    }
                }               
                readFile.close();
            } catch (Exception e) {
                System.out.println("can't open a file : " + e.getMessage());
            }   
        }
    }
}

2018/05/14 15:47

聂金鹏

import java.io.File;
import java.util.Scanner;

public class FindFile {
    public static void main(String[] args) {
        find(".\\src\\A", "LIFE IS TOO SHORT");
    }

    private static void find(String path, String msg) {
        File file = new File(path);
        if (file.isDirectory())
            for (File f : file.listFiles()) {
                if (f.isFile())
                    try {
                        Scanner sc = new Scanner(new File(f.getPath()));
                        while (sc.hasNextLine())
                            if (sc.nextLine().contains(msg)) {
                                System.out.println(f.getPath());
                                break;
                            }
                    } catch (Exception e) {}
                find(f.getPath(), msg);
            }
    }
}

2018/06/01 16:51

김지훈

Python

import os

def search(s):
    for (path, dirs, files) in os.walk(s):
        for file in files:
            if '.txt' in file:
                f = open(os.path.join(path, file), 'r')
                txt = f.read()
                if 'LIFE IS TOO SHORT' in txt:
                    print("{}/{}".format(path, file))
                f.close()

search(".")

2018/06/04 15:18

Taesoo Kim

import os
A = "c:\\temp"
for root, dirs, files in os.walk(A):
    for file in files:
        file_name = root + '\\' + file
        with open(file_name, 'r') as f:
            if f.read().find('LIFE IS TOO SHORT') != -1:
                print(file_name)

#Output:
# c:\temp\test1.txt
# c:\temp\AUtempR\test3.txt

2018/06/22 23:53

재즐보프

// 파일찾기
package com.company;

import java.io.*;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String path = sc.next(); // 경로를 입력받는다
        try {
            getAns(path);
        } catch (FileNotFoundException e) {
            System.out.println("파일 없음");
        } catch (IOException e) {
            System.out.println("에러");
        }
    }

    public static void getAns(String path) throws IOException
    {
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        for (File file : listOfFiles)
        {
            if (file.isFile())
            {
                getStr(file);
            }
            else if(file.isDirectory())
            {
                getAns(file.getPath());
            }
        }
    }

    public static void getStr(File file) throws IOException {
        String name = file.getName();
        if(name.substring(name.length() - 3, name.length()).equals("txt"))
        {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String st = "";
            while((st = br.readLine()) != null)
            {
                if(st.contains("LIFE IS TOO SHORT"))
                {
                    System.out.println(file.getPath());
                }
            }
        }
    }
}

2018/07/12 19:04

이동수

import os

for (path, dir, files) in os.walk("==PATH=="):    
    for filename in files:
        if os.path.splitext(filename)[-1] == '.txt':
            with open(path+'\\'+filename,'r') as tmp:
                text = tmp.read()
                if text.find('LIFE IS TOO SHORT') != -1:
                    print(path,'\\',filename,sep='')


2018/07/16 21:32

Creator

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace CD018
{
    class Program
    {
        static void Main(string[] args)
        {
            string startDir = @"D:\사용자지정디렉토리명";
            string extFilter = "*.txt";
            string checkString = "LIFE IS TOO SHORT";
            foreach (var e in GetFileList(startDir, extFilter, checkString))
            {
                Console.WriteLine(e);
            }
        }
        static List<string> GetFileList(string startDir, string extFilter, string checkString)
        {
            List<string> result = new List<string>();

            try
            {
                result = Directory.EnumerateFiles(startDir, extFilter, SearchOption.AllDirectories)
                    .Where(f => File.ReadAllText(f).Contains(checkString)).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }
            return result;
        }
    }
}

2018/08/20 17:08

mohenjo

import os
def func(dirname):
    for root, dirs, files in os.walk(dirname): # root:어떤디렉토리 , dirs: root아래의 디렉토리모음, files: root아래의 파일모음

        for name in files: #files만큼 돌림
            if '.txt' in name: #file에 '.txt'확장자가 있으면
                f = open(os.path.join(root,name),"r")
                txt = f.read()
                if "Life is too short" in txt:
                    print(name)
                f.close()
func('/')






2018/08/24 13:40

S.H

# python 3.7.1
import glob
print(list(file for file in glob.iglob('A/**/*.txt', recursive=True) if 'test' in open(file).read()))

2018/11/14 17:01

정지환

def search_text(path):

  filenames = os.listdir(path)
  for filename in filenames:
    if os.path.isdir(filename):
      search_text(os.path.join(path, filename))

    else:
      full_filename = os.path.join(path, filename)
      if os.path.splitext(full_filename)[-1] == '.txt':
        f = open(full_filename, 'rt', encoding='utf-8')

        text = f.read()
        if 'LIFE IS TOO SHORT' in text:
          print(full_filename)
        f.close()

2018/12/05 22:27

Gerrad kim

점프 투 파이썬을 참고하며 풀어보았습니다.

os라는 모듈에 대해서 좀 더 자세히 알게 되었습니다.

import os

def search(direc):

    for fn in os.listdir(direc):

        ext = os.path.splitext(fn)[-1]
        if ext == '.txt':
            f = open(direc+fn,'r')
            if 'LIFE IS TOO SHORT' in f.read():
                print(fn)

search('c:/')

2019/01/24 12:13

김영성

import os

def find_str(dirname):
    for (path, dirs, files) in os.walk(dirname):
        for filename in files:
            if '.txt' in filename:
                with open(os.path.join(path, filename), 'r') as file:
                    txt = f.read()
                    if 'LIFE IS TOO SHORT' in txt:
                        print(filename)

find_str('c:/')

2019/01/28 14:52

D.H.

import os

in_text=''
for (path,dir,files) in os.walk("./"):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        if ext=='.txt':
            f = open('%s%s'%(path,filename))
            in_text = f.read()
            f.close()
            if in_text.find('LIFE IS TOO SHORT') != -1:
                print(filename)

2019/02/18 15:32

    class Program
    {
        static int count = 1;
        static void Main(string[] args)
        {
            DirFileSearch(@"D:\source", "txt","LIFE IS TOO SHORT");
        }
        static void DirFileSearch(string path, string file, string strChk)
        {
            try
            {
                string[] dirs = Directory.GetDirectories(path); 
                string[] files = Directory.GetFiles(path, $"*.{file}");

                foreach (string f in files)
                {
                    // 이 곳에 해당 파일을 찾아서 처리할 코드를 삽입하면 된다.   
                    if (File.ReadAllText(f).Contains("LIFE IS TOO SHORT"))
                        Console.WriteLine($"[{count++}] path - {f}");
                }
                if (dirs.Length > 0)
                {
                    foreach (string dir in dirs)
                    {
                        //재귀호출
                        DirFileSearch(dir, file, strChk);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }

2019/04/25 22:19

정태식

import os
A = "c:\\Temp"
Text = "Hello World"
for root,dirs, files in os.walk(A):
    for file in files:
        file_name = root+"\\"+file
        with open(file_name, 'r') as f:
            if f.read().find(Text) != -1:
                print(root+"\\"+file)

2019/10/24 23:04

semipooh

def find(dirname):
    for (path, dir, files) in os.walk(dirname):
        for filename in files:
            if '.txt' in filename:
                f = open(os.path.join(path, filename),'r')
                txt = f.read()
                if 'LIFE IS TOO SHORT' in txt: 
                    print(filename)

                f.close()

find("/Users/git/coding_practice")

2020/01/17 16:36

김민규

import os

s_file = "LIFE IS TOO SHORT" for (path, dir, files) in os.walk("."): for filename in files: f_name = os.path.join(path,filename) try: with open(f_name) as f: if s_file in f.read(): print(filename) except : pass```{.python}

``````{.python} import os

s_file = "LIFE IS TOO SHORT" for (path, dir, files) in os.walk("."): for filename in files: f_name = os.path.join(path,filename) try: with open(f_name) as f: if s_file in f.read(): print(filename) except : pass ```

2020/01/21 16:06

김태완

파이썬 입니다.

import os

def finder(dirname):
    for path, dirs, files in os.walk(dirname):
        for name in files:
            if '.txt' in name:
                with open(os.path.join(path, name),'r') as f:
                    txt=f.read()
                    if 'LIFE IS TOO SHORT' in txt:
                        print(name)

if __name__ == "__main__":

    finder()   

추천 2개 받으신분 코드를 with문으로 변경해 봤네요 ㅋ

2020/03/07 01:12

data big

import os
import re
p = re.compile('(LIFE IS TOO SHORT)')
q=[]
def search(dirname):
    n=0    
    print(dirname+' 디렉토리를 탐색합니다▼')
    try:
        filenames = os.listdir(dirname)
        print('디렉토리 내의 파일 리스트는 '+str(filenames)+'입니다.')
        for filename in filenames:
            full_filename = os.path.join(dirname, filename)
            print(full_filename+'->디렉토리인가 파일인가?')
            if os.path.isdir(full_filename):#이 파일이 디렉토리이면
                print('디렉토리 입니다.')
                search(full_filename)
            else:
                ext = os.path.splitext(full_filename)[-1]#확장자 변수 생성
                print('파일 입니다.')
                if ext == '.txt':
                    f = open(full_filename, 'r')
                    print('파일을 열었습니다. 매칭 검사를 시작합니다.')
                    lines=f.readlines()
                    for line in lines:
                        m = p.search(line)
                        if m:
                            n+=1
                            print('매칭 되는 문자열 확인.★')
                            break
                        else:
                            continue
                    f.close()
                    if n>0:
                        q.append(full_filename)
                        n=0
                    else:
                        print('매칭 되는 문자열이 없습니다.')
                        pass
        print(dirname+' 디렉토리 탐색을 종료합니다.▲')
    except PermissionError:
        pass
search("C:/A/")
print('조건에 부합하는 파일 리스트는  '+str(q)+' 입니다.')

이 문제를 풀면서 하위 디렉토리 검색과 파일 읽기에 더해 정규표현식까지 다양한 방식의 프로그래밍 기법을 연습할 수 있어 좋았습니다. ^^ 유익한 문제 올려주셔서 정말 감사합니다!

2020/03/30 22:35

di figo

import os
import re

def sub_dir(path, w):

    files = os.listdir(path)
    for file in files:
        file_path = os.path.join(path, file)

        if os.path.isdir(file_path):
            sub_dir(file_path, w)
        else:
            with open(file_path, 'r') as f:
                for line in f.readlines():
                    m = w.findall(line)
                    if m:
                        file_list.append(os.path.basename(file_path))
                        return file_list

def main():
    path = input('상위 디렉토리 경로를 입력하세요: ')
    words = input('검색할 문장 또는 단어를 입력하세요: ')

    w = re.compile(words)
    print(sub_dir(path, w))

if __name__ == '__main__':
    file_list = []
    main()

2020/04/12 17:27

Hwaseong Nam

os.walk과 같이 간단히 짤 수 있는 모듈이 있지만, 재귀공부해본다고 해봤네요. 그런데 엉터리 재귀가 된거 같다능 - Hwaseong Nam, 2020/04/12 17:29
import os
cur_path = "D:/A"
os.chdir(cur_path)

for root, dirs, files in os.walk(cur_path, topdown=False):
    for filename in files:
        (name, ext) =  os.path.splitext(filename) 
        if ext == '.txt':
            file_path = os.path.join(root, filename)
            f = open(file_path)
            for line in f.readline():
                if line.find('LIFE IS TOO SHORT'):
                    print('Found {}'.format(file_path))
                    break

2020/07/30 13:16

Chang-Hoon Lee

import os

for (path, dir, files) in os.walk(input()):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        if ext == '.txt':
            for i in filename:
                 try:
                    with open(filename,'r') as f:
                        if "LIFE IS TOO SHORT" in f.read():
                            print("%s/%s" % (path, filename))
                 except FileNotFoundError:
                            pass

2020/11/23 19:48

김우석

def search1(dirname):

        for (path, dir, files) in os.walk(dirname):
            for filename in files:
                ext = os.path.splitext(filename)[-1]
                full_filename = os.path.join(path, filename)
                if ext == '.txt':
                    f = open(full_filename, 'r')
                    try:
                        lines = f.readlines()
                        if 'LIFE IS TOO SHORT' in lines:
                            print(full_filename)
                            print("LIFE IS TOO SHORT")
                        f.close()
                    except:
                        pass

search1('C:/Users/dseok.shin/')

2020/12/02 08:51

DSHIN

import os
import re
def search_s(filename):
    p = re.compile('[LIFE IS TOO SHORT]')
    with open(filename, 'r') as f:
        data = f.read()
    if(p.search(data)):return 1
    else: return 0


def search(dirname):
    filenames = os.listdir(dirname)
    for filename in filenames:
        full_filename = os.path.join(dirname, filename)
        if os.path.isdir(full_filename):
            search(full_filename)
        else:
            ext = os.path.splitext(full_filename)[-1]
            if ext == '.txt':
                a = search_s(full_filename)
                if(a):
                    print(full_filename)

search("c:/A/")                

파일 입출력 너무 어렵네욤

os.walk 사용했을 때 하위 디렉토리부터 찾게 해봤습니다.

import os
import re
def search_s(filename):
    p = re.compile('[LIFE IS TOO SHORT]')
    with open(filename, 'r') as f:
        data = f.read()
    if(p.search(data)):return 1
    else: return 0


def search(dirname):
    for (path, dir, files) in os.walk(dirname, topdown = False):
        for filename in files:
            full_filename = os.path.join(path, filename)
            ext = os.path.splitext(filename)[-1]
            if ext == '.txt':
                a = search_s(full_filename)
                if(a):
                    print(full_filename)

search("c:/A/")                

2020/12/28 18:06

guma go

def search(dirname):
    try:
        filenames= os.listdir(dirname)
        for filename in filenames:
            full_name = os.path.join(dirname,filename)
            if os.path.isdir(full_name):
                search(full_name)
            else:
                ext = os.path.splitext(full_name)[-1]
                if ext=='.txt':
                    file = open(full_name,'r')
                    if "LIFE IS TOO SHORT" in file.read():
                        print(full_name)
                    file.close()
    except PermissionError:
        pass

2020/12/28 23:29

hankyu

import os

src_dir = input("> ")

for path, dir, files in os.walk(src_dir):
    for file in files:
        if file[-4:] == '.txt':
            fl_path = os.path.join(path, file)
            with open(fl_path, 'rt', encoding = 'utf-8') as f:
                txt = f.read()
                if 'LIFE IS TOO SHORT' in txt:
                    print(fl_path)

2021/02/26 04:32

asdfa

import pyautogui as pag
import glob
import os


def makeAns(folder):
    list1 = glob.glob(folder + "/*")
    for files in list1:
        if os.path.isdir(files):
            makeAns(files)
        elif files[-3:] == "txt":
            with open(files, "r") as f:
                str1 =f.read()
                if str1.find("LIFE IS TOO SHORT") >= 0:
                   print(files)
        else:
            continue


makeAns(pag.prompt("폴더경로를 입력하세요."))

2021/04/21 14:11

와장창

#codingdojing_findingFile_re

import os
import glob

"""
1. dirname 이라는 디렉토리 하위의 폴더 전부 조사 isdir
2. 확장자가 txt면 오픈 후 read
3. 파일명 프린트
"""

def findingFile(dirname):

    try:
        filenames = os.listdir(dirname) #폴더 내의 파일들 조사, 파일명

        for filename in filenames:
            full_filename = os.path.join(dirname, filename)

            if os.path.isdir(full_filename):        #폴더면 아래까지 다시
                findingFile(full_filename)
            else:                                   #파일일 때,
                ext = os.path.splitext(full_filename)[-1] # ('D:\\python doit\\codingdojang\\test', '.py')

                if ext == '.txt':    # 확장자 기준으로          # 그냥 'in str' 처럼 해도 될듯
                    with open(full_filename, 'r') as fr:
                        if "Life is too short" in fr.read():
                            print(full_filename)

    except PermissionError as e:       #권한 없는 dir
        print(e)

#findingFile end    

def findingFile2(dirname):      #glob 모듈 사용

    try:
        for filename in glob.glob(dirname):     #이때 filename은 path까지 포함.

            if os.path.isdir(filename):     
                findingFile2(filename+'\\*')
            elif '.txt' in filename:
                with open(filename, 'r') as fr:
                    if "Life is too short" in fr.read():
                        print(filename)

    except PermissionError as e:
        print(e)

#findingFile2 end    

def findingFile3(dirname):      #os.walk를 쓰면 앞에 것들이랑 결과 순서가 조금 다르다.

    try:
        for (_path, _dirs, _files) in os.walk(dirname):
            for filename in _files:                         #얘는 딱 filename만 지칭
                if '.txt' in filename:
                    with open(os.path.join(_path,filename), 'r') as fr:     #오류가 안나려면 filename말고 혹시 모르니 path도 함께
                        if "Life is too short" in fr.read():
                            print(f'{_path}\\{filename}')  #path 를 더해줘야함


    except PermissionError as e:
        print(e)

#findingFile3 end

def findingFile4(dirname):

    try:
        for filename in glob.iglob(dirname+'\\**\\*.txt', recursive=True): #이때 filename은 path까지 포함. iterator로 생성함
            with open(filename, 'r') as fr:
                if "Life is too short" in fr.read():
                    print(filename)

    except PermissionError as e:
        print(e)

#findingFile4 end 

findingFile("D:\\python doit\\codingdojang")
findingFile2("D:\\python doit\\codingdojang")
findingFile3("D:\\python doit\\codingdojang") 
findingFile4("D:\\python doit\\codingdojang")    

*점프투 파이썬 내용을 참고하여 네 가지 방식으로 만들어 보았습니다.

2021/07/20 11:27

Jaeman Lee

import os
root = 'C:/A'

def filesearch (root, sentence) :
    b = os.listdir(root)
    for k in b :
        if os.path.splitext(k)[-1] == '.txt' :
            f1 = open(os.path.join(root,k), 'r')
            c= f1.read()
            if sentence in c :
                print(k)


for (root,dirs,file) in os.walk(root) :
    filesearch(root,'LIFE IS TOO SHORT')

2021/12/20 19:32

양캠부부

import re
import glob

result_list = []
p = re.compile("\bLIFE IS TOO SHORT\b")

def search_txt(path):

    glist = glob.glob(path)

    for tfile in glist:
        tfile2 = tfile.split('.')

        if len(tfile2) == 2 and tfile2[1] == "txt" :
            f1 = open(tfile.'r')
            data = f1.read()

            if p,search(data): result_list.append(tfile)
            f1.close()

        elif len(tfile2) == 1:
            search_txt(tfile)

2022/01/05 18:18

강태호

import os

rootdir = os.getcwd()

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        filepath = subdir + os.sep + file

        if "LIFE IS TOO SHORT" in file:
            print (filepath)

2022/02/07 19:24

로만가

import glob
import os

def findfiles():
    dir_name = input("검색하려는 디렉토리를 입력하세요: ")     # 검색하고자 하는 디렉토리 입력
    filesList = glob.glob(dir_name + '/' + '**', recursive=True)     # 디렉토리(하위 디렉토리 포함: recursive=True, '**'사용)에 있는 파일목록을 리스트로 저장
    result = []       # 결과를 저장할 빈 리스트 생성

    for file in filesList:
        # filesList 의 목록을 파일명(name)과 확장자(ext)로 분리
        name, ext = os.path.splitext(file)
        # 목록중 확장자가 '.txt' 이고 파일 내용 중 'LIFE IS TOO SHORT'이 있으면 파일명을 저장
        if ext == '.txt' and open(file, 'r').read().find('LIFE IS TOO SHORT') == 0:
            result.append(file)

    return result

2022/04/06 17:27

Charles

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os
 
def search(dirname):
    try:
        filenames = os.listdir(dirname)
        for filename in filenames :
            if '.txt' in filename:
                full_filename = os.path.join(dirname, filename)
                if os.path.isdir(full_filename):
                    search(full_filename)
                else:
                    with open(full_filename,'r'as f:
                        text = f.read()
                        if "LIFE IS TOO SHORT" in text:
                            print(filename)
                        f.close()
    except PermissionError:
        pass
 
search("A")
cs

2022/04/12 15:15

Jongjun Lee

파이썬입니다.
import os
def searchall(directory):
    result = []
    for (path,dir,files) in os.walk(directory):
        for file in files:
            ext = os.path.splitext(file)[-1]
            if ext == '.txt':
                f=open(f'{path}\\{file}','r')
                data = f.read()
                if "LIFE IS TOO SHORT" in data:
                    result.append(f'{path}\\{file}')
                f.close()
    return result

2022/06/14 16:58

김시영

import os

def FindTextFileByStringContent(targetFolderPath, stringPattern):
    for currentDirectory, dirs, files in os.walk(str(targetFolderPath)):
        for file in files:
            try:
                targetFilePath = currentDirectory + os.sep + file
                filename, file_extension = os.path.splitext(targetFilePath)
                if file_extension == '.txt':
                    with open(targetFilePath, encoding="utf8") as f:
                        if f.read().find(stringPattern) >= 0:
                            print(targetFilePath)
            except IOError as error:
                print(error)
                pass

FindTextFileByStringContent("C:\\repo", "LIFE IS TOO SHORT")

2023/04/20 09:41

졸린하마

import glob
directory = "test"

def fileSearch(directory):
    fLst = []
    ### 하위 디렉터리에서까지 파일명 받기
    for fn in glob.glob(f'{directory}/**', recursive=True):
        print(fn)
        seperate = fn.split("\\")
        print(seperate)
        if '.' in seperate[-1]:
            ### 하위 디렉터리 파일까지 열기.
            f_ = open('/'.join(seperate), 'r')
            data_f_ = f_.readlines()
            if 'LIFE IS TOO SHORT.' in data_f_:
                fLst.append(seperate[-1])
            f_.close()

    return fLst

print(fileSearch(directory))

2023/08/08 07:28

Hawk Lee

JAVA입니다.

package question1.파일찾기;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class FindFile {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        List<File> files = getFiles(new File("C:/A"));
        for (File file : files) {
            System.out.println(file);
        }
    }

    public static List<File> getFiles(File dir) throws Exception {
        File[] files = dir.listFiles();
        List<File> containFiles = new ArrayList<File>();
        for (File file : files) {
            if(file.isFile()) {
                if(file.toString().split("\\.")[1].equals("txt")) {
                    FileReader fr = new FileReader(file);
                    char[] chars = new char[65536];
                    fr.read(chars);
                    String str = new String(chars);
                    if(str.contains("LIFE IS TOO SHORT")) {
                        containFiles.add(file);
                    }
                }
            }
            if(file.isDirectory()) {
                containFiles.addAll(getFiles(file));
            }
        }
        return containFiles;
    }
}

2025/01/21 23:07

박준우

목록으로