zoukankan      html  css  js  c++  java
  • Java读写TXT文本

    public String readTxtFile(String filePath) {
    		StringBuffer appInfolistInput = new StringBuffer();
    		try {
    			String encoding = "UTF8";
    			File file = new File(filePath);
    			if (file.isFile() && file.exists()) {
    				InputStreamReader read = new InputStreamReader(
    						new FileInputStream(file), encoding);
    				BufferedReader bufferedReader = new BufferedReader(read);
    				String lineTxt = null;
    				while ((lineTxt = bufferedReader.readLine()) != null) {
    					appInfolistInput.append(lineTxt);
    				}
    				read.close();
    				bufferedReader.close();
    			} else {
    				System.out.println("找不到指定的文件");
    			}
    		} catch (Exception e) {
    			System.out.println("读取文件内容出错");
    			e.printStackTrace();
    		}
    		return appInfolistInput.toString();
    	}
    
    public void readByte(String fileName) {
    		InputStream is = null;
    		try {
    			is = new FileInputStream(fileName);
    			byte[] byteBuffer = new byte[is.available()];
    			int read = 0;
    			while((read = is.read(byteBuffer)) != -1){
    				System.out.write(byteBuffer, 0, read);
    			}
    		} catch (FileNotFoundException e) {			
    			e.printStackTrace();
    		} catch (IOException e) {			
    			e.printStackTrace();
    		}finally{			
    			try {
    				if(is != null){
    					is.close();
    				}
    			} catch (IOException e) {				
    				e.printStackTrace();
    			}
    		}		
    	}
    
    public void writeBuffer(String fileName){
    		try {
    			File file = new File(fileName);
    			BufferedWriter output = new BufferedWriter(new FileWriter(file));			
    			output.write("hello wrold");
    			output.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    public void writeByte(String fileName){
    		try {
    			File file = new File(fileName);
    			OutputStream os = new FileOutputStream(file);
    			String s = "hello world";			
    			byte[] byteBuffer = s.getBytes();
    			os.write(byteBuffer, 0, byteBuffer.length);
    			os.flush();
    			os.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
  • 相关阅读:
    DataTable转换成List
    gitbash如何修改可恶的蓝色字体
    nvm use exit status 1
    搭建CNPM私有库
    Angular2项目,刷新后页面显示404错误的?
    基于webpack模块加载,ts里对系统对象prototype的扩展
    Angular2 primeNG的p-dropdown的选中值未初始化
    移动端开发常见问题
    weinre的使用
    利用百度地图API进行GPS坐标转换成百度地图坐标,创建点,标签,多边形
  • 原文地址:https://www.cnblogs.com/zhangfei/p/3992191.html
Copyright © 2011-2022 走看看