1. 程式人生 > >txt 檔案在伺服器上的 讀取及寫入

txt 檔案在伺服器上的 讀取及寫入

做的外圍資料對接,報文引數較多,資料庫存不下,只好用txt了, 自己 備用


public class MyFileUtils {
	
	/**
	 * @param txt  寫入的內容   
	 * @param channel   來源
	 * @param name     姓名
	 * @param path   路徑
	 * /opt/tomcat-finance/txt/  qq ljp
	 * @throws IOException
	 */
	public static void writer(String txt,String channel,String name,String path) throws IOException {
		//		path-->/opt/tomcat-finance/txt/
		FileWriter fw=null;
		BufferedWriter bw=null;
		File file1 = new File(path+channel+name+".txt");
		if(file1.exists()) {
			file1.deleteOnExit();
		}
        try {
            fw = new FileWriter(file1);
            bw = new BufferedWriter(fw);
            bw.write(txt);
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bw.close();
            fw.close();
		}
	}
	
	/**
	 * 檔案內容讀取
	 * @param name(需要加字尾)
	 * @param path
	 * @return 文字
	 */
	public static String read(String name,String path){
		//		path-->/opt/tomcat-finance/txt/
        File file = new File(path+name);
        if(!file.exists()) {
        	return null;
        }
        String readData=null;
        StringBuffer reString=new StringBuffer() ;
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(file), "UTF-8") );
        //    BufferedReader br = new BufferedReader(fr);
            try{
            	while((readData = br.readLine())!=null){
                	reString.append(readData);
                }
            }catch (Exception e){
                    e.printStackTrace();
            }finally {
            	br.close();
            	fr.close();
			}
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
		return reString.toString();
	}
	
	public static void main(String[] args) {
		String read = MyFileUtils.read("qqe549c8dc64e9ca680164e9d87b670069.txt","C:\\Users\\Administrator\\Downloads\\");
		System.out.println(read);
	}
	
}