자바 문자열,list 를 파일 에 기록 하고 내용 을 읽 는 사례

긴 말 안 할 게 요.그냥 코드 보 세 요~

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.util.List; 
import android.graphics.Bitmap; 
public class FileUtils {
 
	/**
	 *          txt
	 */
	@SuppressWarnings("resource")
	public static void FileString(String path, String data) {
		try {
			FileWriter writer = new FileWriter(path);//    
			writer.write(data);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	/**
	 *      txt
	 * 
	 * @param path
	 * @param data
	 */
	@SuppressWarnings("resource")
	public static void FileString2(String path, String data) {
		try {
			FileOutputStream outputStream = new FileOutputStream(path);//    
			outputStream.write(data.getBytes());
			outputStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	/**
	 *          txt
	 * 
	 * @param path
	 * @param data
	 */
	public static void FileString3(String path, String data) {
		try {
			OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");//       
			writer.write(data);
			writer.close();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	/**
	 *      txt
	 * 
	 * @param path
	 * @param data
	 */
	@SuppressWarnings("resource")
	public static void FileString4(String path, String data) {
		try {
			FileOutputStream outputStream = new FileOutputStream(path, true);//     
			outputStream.write(("\r
" + data).getBytes()); outputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * list * * @param path * @param list */ @SuppressWarnings("resource") public static <T> void FileWriteList1(String path, List<T> list) { try { FileOutputStream outputStream = new FileOutputStream(path); ObjectOutputStream stream = new ObjectOutputStream(outputStream); stream.writeObject(list); stream.close(); outputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * list txt * * @param path * @param list */ @SuppressWarnings("resource") public static <T> void FileWriteList(String path, List<T> list) { try { BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(path), "UTF-8")); for (T s : list) { bufferedWriter.write(s.toString()); bufferedWriter.newLine(); bufferedWriter.flush(); } bufferedWriter.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * bitmap * * @param path * @param bitmap */ @SuppressWarnings("resource") public static void FileBitmap(String path, Bitmap bitmap) { try { FileOutputStream outputStream = new FileOutputStream(path); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); outputStream.flush(); outputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * * * @param path */ @SuppressWarnings("resource") public static String FileInputString(String path) { StringBuffer buffer = new StringBuffer(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8")); String data = null; while ((data = reader.readLine()) != null) { buffer.append(data + "\r
"); } reader.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return buffer.toString(); } /** * * * @param path * @return */ @SuppressWarnings("resource") public static String FileInputString2(String path) { StringBuffer buffer = new StringBuffer(); try { FileInputStream inputStream = new FileInputStream(path); byte[] bytes = new byte[1024]; int bytead = 0; while ((bytead = inputStream.read(bytes)) != -1) { buffer.append(new String(bytes, 0, bytead)); } inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return buffer.toString(); } /** * list * * @param path */ @SuppressWarnings("resource") public static <T> void FileInputList(String path) { try { FileInputStream inputStream = new FileInputStream(path); ObjectInputStream stream = new ObjectInputStream(inputStream); List<T> list = (List<T>) stream.readObject(); inputStream.close(); stream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * * @param path * @return */ @SuppressWarnings("resource") public static String FileInput3(String path) { StringBuffer buffer = new StringBuffer(); try { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(path), "UTF-8")); String data = null; while ((data = bufferedReader.readLine()) != null) { buffer.append(data+"\r
"); } bufferedReader.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return buffer.toString(); } }
추가 지식:자바 읽 기 txt 파일 은 List
파일 은 데스크 톱 에 hello.txt 라 는 이름 을 두 고 읽 을 내용 을 먼저 봅 니 다.

데모 가 마음대로 쓰 는 것 을 편리 하 게 보 여주 기 위해 서 입 니 다.형식 은 한 줄 에 한 줄 씩 영어 단어 로 모두 다섯 개 입 니 다.
코드 를 읽 고 이 코드 도 인터넷 에서 찾 았 는데 어느 블 로 그 를 잊 어 버 렸 어 요.

import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author :
 * @date : 2018/8/30
 * @description:
 */
public class ReaderFileLine {
 
  /**
  * @author:
  * @date:2018/8/30
  * @description: txt    List<String>
  */
  public static List<String> getFileContent(String path) {
    List<String> strList = new ArrayList<String>();
    File file = new File(path);
    InputStreamReader read = null;
    BufferedReader reader = null;
    try {
      read = new InputStreamReader(new FileInputStream(file),"utf-8");
      reader = new BufferedReader(read);
      String line;
      while ((line = reader.readLine()) != null) {
        strList.add(line);
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (read != null) {
        try {
          read.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
 
    }
    return strList;
  }
 
  public static void main(String[] args) {
    List<String> fileContent = 
    ReaderFileLine.getFileContent("C:\\Users\\Lenovo\\Desktop\\hello.txt");
    for (String s : fileContent) {
      System.out.println(s);
    }
  }
 
}
출력:
first
second
Third
Fourth
Fifth
주의:
1.여기 File 클래스 가 져 온 가방 은 Io 의 것 이지 Nio 의 것 이 아 닙 니 다.
2. ReaderFileLine.getFileContent("C:\\Users\\Lenovo\\Desktop\\hello.txt"); 이 경 로 는 절대 경로 입 니 다.
3.경 로 는 역 슬 래 쉬 입 니 다\\하지만 코드 에 서 는 역 슬 래 쉬 가 전의 라 는 뜻 이 므 로\를 하나 더 추가 해 야 합 니 다.만약 당신 이 사용 하 는 IDEA 가 축하한다 면 자동 으로 추 가 됩 니 다.
이상 의 자바 는 문자열,list 를 파일 에 기록 하고 내용 을 읽 는 사례 는 바로 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.참고 하 시기 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기