读取txt内容写到新的txt中

 

public static void main(String[] args) throws SQLException {
		JavaTools jt = new JavaTools();
		jt.createTxt(excuteReadTxt("C:/Users/Administrator/Desktop/oldTxt.txt"), 7, "C:/Users/Administrator/Desktop/newTxt.txt");
		System.out.println("-----------over");
	}

 

createTxt方法:

    public static void createTxt(List<Object[]> values,int objSize,String file){
    	StringBuffer row=null;
    	OutputStreamWriter osw = null;
    	try {
    		osw = new OutputStreamWriter(new FileOutputStream(file,true),"GBK");
    		for(int i=0 ; i<values.size() ; i++){
    			row = new StringBuffer();
    			Object[] obj = values.get(i);
    			for(int j = 0 ; j<objSize ; j++){
    				if(objSize-j == 1){
    					row.append(obj[j]+"\r\n");//换行
    				}else{
    					row.append(obj[j]+"\t");//tab键
    				}
    			}
    			osw.write(row.toString());
    		}
    		values.clear();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
       	 if(osw!=null)//if(osw!=null)
             try {
             	osw.close();//osw.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
      }
    }

 excuteReadTxt方法:

/**执行readTxt方法*/
    public static List<Object[]> excuteReadTxt(String filePath){
		Map<Integer,List<Object>> map = readTxt(new File(filePath));
		List<Object[]> objs = new ArrayList<Object[]>();
		Iterator<Entry<Integer, List<Object>>> iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
			Entry<Integer, List<Object>> entery = iterator.next();
			int key = entery.getKey();
			List<Object> values = entery.getValue();
			Object[] ss = new Object[values.size()];
			for(int i = 0 ; i<values.size() ; i++){
				ss[i] = values.get(i);
			}
			objs.add(ss);
		}
		return objs;
    }

 readTxt方法:

   public static Map<Integer,List<Object>>  readTxt(File file){
    	//jt.readTxt(new File("C:/Users/Administrator/Desktop/aaaaa.txt"));
    	BufferedReader br = null;
    	Map<Integer,List<Object>> map = new HashMap<Integer, List<Object>>();
    	List<Object> values = null;
    	int key = 1;
    	try {
    		InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GBK");
    		br = new BufferedReader(read);
    		String temp = null;
    		while ((temp = br.readLine()) != null) {
    			if("".equals(temp)){
    				continue;
    			}
    			values = new ArrayList<Object>();
    			StringTokenizer st = new StringTokenizer(temp);
    			while(st.hasMoreElements()){
    				String num = st.nextToken("\t").trim();
    				values.add(num);
    			}
    			map.put(key, values);
    			key++;
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(null != br){
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return map;
    }

 

 

你可能感兴趣的:(txt)