java IO实现一次性读取一个文件全部内容后在写入一个文件
import java. io. * ;
public class FileIo { public static void main ( String [ ] args) { String content = getFileString ( ) ; File outputFile = new File ( "C:\\Users\\admin\\Desktop\\test\\1.txt" ) ; try ( FileOutputStream fileOutputStream = new FileOutputStream ( outputFile) ; BufferedWriter bufferedWriter = new BufferedWriter ( new OutputStreamWriter ( fileOutputStream) ) ) { bufferedWriter. write ( content) ; bufferedWriter. flush ( ) ; } catch ( IOException e) { e. printStackTrace ( ) ; } } public static String getFileString ( ) { StringBuilder contentBuilder = new StringBuilder ( ) ; File file = new File ( "C:\\Users\\admin\\Desktop\\test\\2.txt" ) ; FileInputStream fileInputStream = null ; InputStreamReader inputStreamReader = null ; BufferedReader bufferedReader = null ; String content = "" ; try { fileInputStream = new FileInputStream ( file) ; inputStreamReader = new InputStreamReader ( fileInputStream) ; bufferedReader = new BufferedReader ( inputStreamReader) ; String line; while ( ( line = bufferedReader. readLine ( ) ) != null ) { contentBuilder. append ( line) ; contentBuilder. append ( System . lineSeparator ( ) ) ; } content = contentBuilder. toString ( ) ; } catch ( IOException e) { e. printStackTrace ( ) ; } finally { try { if ( bufferedReader != null ) { bufferedReader. close ( ) ; } } catch ( IOException e) { e. printStackTrace ( ) ; } try { if ( inputStreamReader != null ) { inputStreamReader. close ( ) ; } } catch ( IOException e) { e. printStackTrace ( ) ; } try { if ( fileInputStream != null ) { fileInputStream. close ( ) ; } } catch ( IOException e) { e. printStackTrace ( ) ; } } return content; }
}