Java 행 읽기 파일 행 쓰기 및 공백으로 문자열을 분할하는 방법

우선 줄별로 문자열을 읽습니다.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class TxtChange {
 public static void main(String[] args){ 
  File file=new File("E:\\oldData.txt"); 
  BufferedReader reader=null; 
  String temp=null; 
  int line=1; 
  try{ 
    reader=new BufferedReader(new FileReader(file)); 
    while((temp=reader.readLine())!=null){ 
     // System.out.println(" "+line+" :"+temp);

     String string=AnalyzeStr.getAnalyze().getNewString(temp);// 
     System.out.println(string);
     AnalyzeStr.getAnalyze().saveRecordInFile(string);// 
     line++; 
    } 
  } 
  catch(Exception e){ 
   e.printStackTrace(); 
  } 
  finally{ 
   if(reader!=null){ 
    try{ 
     reader.close(); 
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
    } 
   } 
  } 
 } 
}
공백에 따라 문자열을 분할하고 새 문자열로 재조합합니다
비어 있는 것은\s이고 이스케이프 문자입니다.\s, +는 하나 이상의 공백을 나타냅니다.

public String getNewString(String fileName){
  String str1="";
  String str2="";
  String str3="";
  String []arrayStr=fileName.split("\\s+");
  str1="
\t\t"+arrayStr[0]; str2="\t"+arrayStr[1]; str3="\t"+arrayStr[2]; return str1+str2+str3; }
그리고 줄에 따라 문자열을 저장하는 방법입니다. path는 저장된 경로입니다. 예를 들어 "D:/test.txt"

// 
 public void saveRecordInFile(String str) {
  File record = new File(path);// 
  try {
   if (!record.exists()) {

    File dir = new File(record.getParent());
    dir.mkdirs();
    record.createNewFile();
   }
   FileWriter writer = null;
   try {
    //  , true 
    writer = new FileWriter(record, true);
    writer.write(str);
   } catch (IOException e) {
    e.printStackTrace();
   } finally {
    try {
     if (writer != null) {
      writer.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  } catch (Exception e) {
   System.out.println(" ");
  }
 }
위의 자바는 줄에 따라 파일을 읽고 줄에 따라 파일을 쓰고 빈칸으로 문자열을 나누는 방법이 바로 여러분에게 모든 내용을 공유하는 것입니다. 참고하시고 저희를 많이 사랑해 주시기 바랍니다.

좋은 웹페이지 즐겨찾기