码迷,mamicode.com
首页 > 编程语言 > 详细

java读写文件

时间:2016-02-19 12:15:38      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

package file;

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

/**
 *	
 * @author Administrator
 *
 */
public class FileUtil {
	 
	    public static void main(String args[]) {
	        String srcFile = "D:/old.txt";
	        String toFile = "D:/new.txt";
	        try {
	            String result = read(srcFile);
	            write(result, toFile);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	 
	    private static String read(String srcFile) throws FileNotFoundException {
	 
	        Scanner in = new Scanner(new File(srcFile));
	        String result = "";
	 
	        while (in.hasNextLine()) {
	            result += in.nextLine() + "\r\n";
	        }
	 
	        in.close();
	 
	        return result;
	    }
	 
	    private static void write(String result, String toFile) throws Exception {
	        Writer w = new FileWriter(new File(toFile));
	        w.write(result);
	        w.flush();
	        w.close();
	    }
	}

  追加文件

package file;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Writer;

/**
 * 两种方法
 * 追加文件
 * @author Administrator
 *
 */
public class AppendFile {
	public static void Append1() throws IOException{
		String content="---第一种方法添加文件内容-------\r\n6666";
		Writer w = new FileWriter(new File("new.txt"),true);
		w.append(content);
		System.out.println("追加成功");
		String c1="1q1q\r\n";
		w.append(c1);
		w.flush();
		w.close();
	}
	public static void Append2() throws IOException{
		RandomAccessFile randomFile = new RandomAccessFile(new File("D://new.txt"), "rw");  
        // 文件长度,字节数  
        long fileLength = randomFile.length();  
        //将写文件指针移到文件尾。  
        randomFile.seek(fileLength);  
        randomFile.writeBytes("00000xxxxxxxx11111");  
        randomFile.close();  
	}
	public static void main(String[] args) throws IOException {
		Append1();
		Append2();
	}

}

  

java读写文件

标签:

原文地址:http://www.cnblogs.com/JAYIT/p/5200421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!