Ez-Pixel 앱은 개인정보를 수집하지 않습니다

Ez-Pixel 앱은 로그인을 하지 않습니다

Ez-Pixel 앱은 무료로 사용하실 수 있습니다

Ez-Pixel 앱은 전 연령이 안전하게 사용하실 수 있습니다

 

[앱 관련 지원방법]

댓글 또는 메일로 문의 주시기 바랍니다

 

[개인정보처리방침]

Ez-Pixel 앱은 개인정보를 요구하거나 저장하지 않습니다.

 

@implementation ViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    
}
 
// 쓰기
- (IBAction)onWriteFile:(UIButton *)sender {
    // 파일경로 - 앱샌드박스/Documents/test.txt
    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) firstObject];
    NSString *filePath = [directory stringByAppendingPathComponent:@"test.txt"];
    
    // 텍스트
    NSString *text = [self.tfText.text stringByAppendingString:@"\n"];
    
    // 기존파일이 있는지 확인
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    // 기존파일이 없으면 새로생성하여 파일쓰기
    if(!isExist) {
        NSError *error;
        [text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if(error) {
            NSLog(@"File Write Error :%@ ", error.localizedDescription);
        }
    }
    // 기존파일이 있으면 파일핸들러로 파일끝으로 이동하여 파일쓰기
    else {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
        if(fileHandle) {
            // 끝으로 이동
            [fileHandle seekToEndOfFile];
            // NSData로 바꾼후 파일쓰기
            NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
            [fileHandle writeData:data];
            [fileHandle closeFile];
        }
    }
}
 
// 읽기
- (IBAction)onReadFile:(UIButton *)sender {
    // 파일경로 - 앱샌드박스/Documents/test.txt
    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) firstObject];
    NSString *filePath = [directory stringByAppendingPathComponent:@"test.txt"];
    
    // 파일읽기
    NSString *text = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if(text) {
        [self.lbText setText:text];
    }
}
 
@end
 
cs

'IT > Ⅰ. IOS' 카테고리의 다른 글

[IOS] GPS 현재 위치 가져오기  (0) 2025.07.07
[IOS] TTS 사용  (7) 2025.07.06
[IOS] FCM Crashlytics 로그  (2) 2025.07.06
[IOS] FCM 발송  (0) 2025.06.30
[IOS] GIF, SVG, APNG 이미지 사용  (0) 2025.05.22
public class MainActivity extends AppCompatActivity {
 
    EditText editText;
    TextView text;
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = findViewById(R.id.editText);
        text = findViewById(R.id.text);
 
        Button btnWrite = findViewById(R.id.btnWrite);
        btnWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                writeFile();
            }
        });
 
        Button btnRead = findViewById(R.id.btnRead);
        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                readFile();
            }
        });
    }
 
    // 파일에 쓰기
    public void writeFile() {
        String text = editText.getText().toString() + "\n";
        // 위치 - /data/data/패키지명/files/test.txt
        File file = new File(getFilesDir(), "test.txt");
        // true - 기존 파일에 이어서 쓰기
        try (FileOutputStream fos = new FileOutputStream(file, true)) {
            fos.write(text.getBytes("UTF-8"));
            fos.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    // 파일에서 읽기
    public void readFile() {
        // 위치 - /data/data/패키지명/files/test.txt
        File file = new File(getFilesDir(), "test.txt");
        try (   FileInputStream fis = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
                BufferedReader br = new BufferedReader(isr); ) {
            // BufferedReader 를 사용하여 한줄씩 읽기
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            fis.close();
 
            text.setText(sb.toString());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
cs

 

  • 내부 저장소에 읽기/쓰기 할때는 따로 권한이 필요하지 않음

 

'IT > Ⅱ. Android' 카테고리의 다른 글

[Android] GPS 현재 위치 가져오기  (1) 2025.07.07
[Android] TTS 사용  (0) 2025.07.06
[Android] FCM Crashlytics 로그  (0) 2025.07.06
[Android] FCM 발송  (1) 2025.06.29
[Android] GIF, SVG, APNG 이미지 사용  (2) 2025.05.21

+ Recent posts