分类:Java


使用正则过滤掉字符串中换行符


private String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern pattern = Pattern.compile("\\s*|\t|\r|\n");
			Matcher matcher = pattern.matcher(str);
			dest = matcher.replaceAll("");
		}
		return dest;
	}

Java实现页面(一)


package checkmod;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class Checkmod extends JFrame implements ActionListener {

private JPanel jp=new JPanel();
private JCheckBox[] jcba={new JCheckBox("豫菜"),new JCheckBox("川菜"),new JCheckBox("粤菜"),new JCheckBox("西餐"),new JCheckBox("其他")};
private JRadioButton[] jrba={new JRadioButton("5~15岁"),new JRadioButton("16~35岁"),new JRadioButton("26~35岁"),new JRadioButton("36~45岁"),new JRadioButton("36~45岁"),new JRadioButton("46~55岁")};
private JButton[] jba={new JButton("确定"),new JButton("取消")};
private JLabel[] jla={new JLabel("年龄段:"),new JLabel("爱好:"),new JLabel("调查结果:")};
private JTextField jtf=new JTextField();
private ButtonGroup bg=new ButtonGroup();
public Checkmod(){
jp.setLayout(null);
for(int i=0;i<5;i++){
jrba[i].setBounds(40+i*100,40,80,30);
jcba[i].setBounds(40+i*120,100,120,30);
jp.add(jrba[i]);jp.add(jcba[i]);
jrba[i].addActionListener(this);
jcba[i].addActionListener(this);
bg.add(jrba[i]);
if(i>1)
continue;
jla[i].setBounds(20, 20+i*50, 80, 30);
jba[i].setBounds(400+i*120, 200, 80,26);
jp.add(jla[i]);jp.add(jba[i]);
jba[i].addActionListener(this);
}
jla[2].setBounds(20, 150, 120, 30);jp.add(jla[2]);
jtf.setBounds(120, 150, 500, 26);jp.add(jtf);
jtf.setEditable(false);
this.add(jp);this.setTitle("食物调查表");
this.setBounds(100, 100, 700, 280);
this.setVisible(true);this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}


public static void main(String[] args) {
// TODO Auto-generated method stub
new Checkmod();
}

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==jba[1]){
for(int i=0;i<jcba.length;i++){
jcba[i].setSelected(false);
jtf.setText("");
}
}else{
StringBuffer temp1=new StringBuffer("你是一个");
StringBuffer temp2=new StringBuffer();
for(int i=0;i<5;i++){
if(jrba[i].isSelected()){
temp1.append(jrba[i].getText());
}
if(jcba[i].isSelected()){
temp2.append(jcba[i].getText()+".");
}
}
if(temp2.length()==0){
jtf.setText("爱好为空???");
}else{
temp1.append("的人,比较喜欢");
temp1.append(temp2.substring(0, temp2.length()-1));
jtf.setText(temp1.append("。").toString());
}
}
}

}

来源连接:https://jingyan.baidu.com/article/f79b7cb319780c9144023ec1.html


ElasticSearch增删改查日记


  public static void main(String[] args) {
  TransportClient client = null;
  try {
  client = new PreBuiltTransportClient(Settings.EMPTY)
  .addTransportAddress(new
  InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
  SearchResponse response = client.prepareSearch()
  .setQuery(QueryBuilders.boolQuery()
  .should(QueryBuilders.rangeQuery("tax_paid").from("452588.45").to("452588.45"))
  .should(QueryBuilders.rangeQuery("cash").from("17573086.76").to("17573086.76"))
  .should(QueryBuilders.wildcardQuery("company_name", "*生物*"))
  )
  .get();
  System.out.println(response.getHits().totalHits);
  for (SearchHit hit : response.getHits().getHits()) {
  System.out.print("index:" + hit.getIndex() + "----");
  System.out.print("type:" + hit.getType() + "----");
  System.out.print("value:" + hit.getSource().get("company_id"));
  System.out.println();
  }
  } catch (UnknownHostException e) {
  e.printStackTrace();
  } finally {
  if (client != null) {
  client.close();
  }
  }
  }

/*
 * 批量操作
 */ 
  public static void main(String[] args) { TransportClient client = null; try {
   String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," +
   "\"message\":\"trying out sadfsdafasdf\"" + "}"; String json2 = "{" +
   "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-31\"," +
  "\"message\":\"trying out aaaaa\"" + "}"; client = new
   PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new
   InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
   BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
   bulkRequestBuilder.add(client.prepareIndex("company", "company_profile", "2")
   .setSource(json)); bulkRequestBuilder.add(client.prepareIndex("company",
   "company_profile", "3").setSource(json2)); BulkResponse responses =
   bulkRequestBuilder.get(); if (responses.hasFailures()) {
   System.out.println(responses.toString()); } } catch (UnknownHostException e)
   { e.printStackTrace(); } finally { if (client != null) { client.close(); } }
   }
  

/*
 * 删除数据
 *
 */
  public static void main(String[] args) {
  TransportClient client = null;
  try {
  client = new PreBuiltTransportClient(Settings.EMPTY)
  .addTransportAddress(new
  InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
  DeleteResponse response = client.prepareDelete("company", "company_profile",
  "1").get();
  System.out.println(response.status());
  } catch (UnknownHostException e) {
  e.printStackTrace();
  } finally {
  if (client != null) {
  client.close();
  }
  }
  }

/*
 * 插入数据
*/
 public static void main(String[] args) { TransportClient client = null;
   try { client = new PreBuiltTransportClient(Settings.EMPTY)
  .addTransportAddress(new
   InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); String
   json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," +
   "\"message\":\"trying out Elasticsearch\"" + "}"; IndexResponse response =
   client.prepareIndex("company", "company_profile").setSource(json,
   XContentType.JSON).get(); String _index = response.getIndex(); String _type =
   response.getType(); String _id = response.getId(); long _version =
   response.getVersion(); System.out.println("index:" + _index + "\ntype:" +
   _type + "\nid:" + _id + "\nversion:" + _version); } catch
   (UnknownHostException e) { e.printStackTrace(); } finally { if (client !=
   null) { client.close(); } } }
 

Java 正则匹配全中文字段


// 按指定模式在字符串查找
String line = "全中文a";
String pattern = "^[\u4e00-\u9fa5]+$";

// 创建 Pattern 对象
Pattern r = Pattern.compile(pattern);

// 现在创建 matcher 对象
Matcher m = r.matcher(line);
System.out.println(m.matches());

BigDecimal计算


加法  a.add(b);

减法 a.subtract(b);

乘法 a.multiply(b);

除法 a.divide(b,需要精确到小数点以后几位,BigDecimal.ROUND_HALF_UP)

java进制转换


//十进制转化为十六进制,结果为C8。

Integer.toHexString(200);

//十六进制转化为十进制,结果140。

Integer.parseInt("8C",16);

SwitchItem


/**
 * 根据下划线字段转驼峰字段
 * 
 * @param item 下划线字段
 * @return 驼峰字段
 */
private String SwitchHump(String item) {
   while (true) {
      if (item.contains("_")) {
         int index = item.indexOf("_");
         String value = item.substring(index + 1, index + 2);
         value = value.toUpperCase();
         item = item.replace(item.substring(index, index + 2), value);
      } else {
         break;
      }
   }
   return item;
}

/**
 * 将驼峰转为下划线
 * 
 * @param item 驼峰字段
 * @return 下划线字段
 */
public String SwitchUnderline(String item) {
   String num = "0123456789";
   String result = "";
   for (int index = 0; index < item.length(); index++) {
      String value = item.substring(index, index + 1);
      if (num.contains(value)) {
         value = "_" + value;
      } else if (Character.isUpperCase(value.charAt(0))) {
         value = "_" + value.toLowerCase();
      }
      result += value;
   }
   return result;
}

Switch


/**
 * 将String转换为数组
 * 
 * @param value 数组格式String字符串
 * @return 数组
 */
public static String[] switchTo(String value) {
   return value.replace("[", "").replace("]", "").replaceAll(" ", "").split(",");
}

/**
 * 遍历数组返回字符串
 * 
 * @param values 数组
 * @return 拼接的字符串
 */
public static String switchToString(String[] values) {
   String result = "";
   if (Util.notEmpty(values)) {
      for (String value : values) {
         result += ",'" + value + "'";
      }
      result = result.replaceFirst(",", "");
   }
   return result;
}

/**
 * 将String集合转化为BigDecimal集合
 * 
 * @param values String集合
 * @return BigDecimal集合
 */
public static List<BigDecimal> switchTo(String[] values) {
   List<BigDecimal> result = new ArrayList<>();
   for (String value : values) {
      if (Util.notEmpty(value)) {
         BigDecimal bigDecimal = new BigDecimal(value);
         result.add(bigDecimal);
      } else {
         result.add(null);
      }
   }
   return result;
}

/**
 * 根据BigDecimal集合获取最大值
 * 
 * @param list BigDecimal集合
 * @return 最大值
 */
public static BigDecimal getMax(List<BigDecimal> list) {
   BigDecimal max = list.get(0);
   for (BigDecimal value : list) {
      if (value.subtract(max).doubleValue() > 0) {
         max = value;
      }
   }
   return max;
}

/**
 * 根据BigDecimal集合获取最小值
 * 
 * @param list BigDecimal集合
 * @return 最小值
 */
public static BigDecimal getMin(List<BigDecimal> list) {
   BigDecimal min = list.get(0);
   for (BigDecimal value : list) {
      if (value.subtract(min).doubleValue() < 0) {
         min = value;
      }
   }
   return min;
}

/**
 * 根据BigDecimal集合获取和 只计算正值
 * 
 * @param list BigDecimal集合
 * @return 集合的和
 */
public static BigDecimal getSum(List<BigDecimal> list) {
   BigDecimal sum = new BigDecimal(0);
   for (BigDecimal value : list) {
      if (value.doubleValue() > 0) {
         sum = sum.add(value);
      }
   }
   return sum;
}

/**
 * 根据开始时间结束时间及报表类型获取具体日期集合
 * 
 * @param from 开始时间
 * @param to 结束时间
 * @param period 报表类型
 * @return 具体日期集合
 */
public static String getTradingDates(int from, int to, String period) {
   String dates = "";
   String[] periods = period.split(",");
   for (String p : periods) {
      for (int i = from; i < to; i++) {
         String date = ExcelUtil.getDateByPeriod(String.valueOf(i), p);
         if (!dates.contains(date)) {
            dates += ",'" + date + "'";
         }
      }
   }
   dates = dates.replaceFirst(",", "");
   return dates;
}

/**
 * 根据其他币种类型及金额转换为人民币
 *
 * @param money 金额
 * @param currency 币种代码
 * @return 人民币金额
 */
public static BigDecimal getRMBByOther(BigDecimal money, String currency) {

   if (money == null || money.toString().contains("-")) {
      return new BigDecimal("0");
   }
   switch (currency) {
      case "RMB":
         return money.setScale(5, BigDecimal.ROUND_HALF_UP);
      case "USD":
         return money.multiply(new BigDecimal(6.617)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "HKD":
         return money.multiply(new BigDecimal(0.848)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "EUR":
         return money.multiply(new BigDecimal(7.82)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "YJP":
         return money.multiply(new BigDecimal(0.0585)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "KRW":
         return money.multiply(new BigDecimal(0.005855)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "CAD":
         return money.multiply(new BigDecimal(5.2983)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "GBP":
         return money.multiply(new BigDecimal(8.7232)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "AUD":
         return money.multiply(new BigDecimal(5.197)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "CHF":
         return money.multiply(new BigDecimal(6.7438)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "SGD":
         return money.multiply(new BigDecimal(4.873)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "TWD":
         return money.multiply(new BigDecimal(0.2189)).setScale(5, BigDecimal.ROUND_HALF_UP);
   }
   return null;
}

DateUtil


/**
 * 获取当前时间的前 day天的日期
 * 
 * @param day 天数
 * @return 字符串格式的前一天日期
 */
public static Date getBeforeDate(int day) {
   Date date = new Date();
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   calendar.add(Calendar.DATE, -day);
   return calendar.getTime();
}

/**
 * 获取某日期距离今天的天数
 *
 * @param date 日期
 * @return 天数
 */
public static int getDateToDay(Date date) {
   Date day = new Date();
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(day);
   int newday = calendar.get(Calendar.DAY_OF_YEAR);
   calendar.setTime(date);
   return newday - calendar.get(Calendar.DAY_OF_YEAR);
}

/**
 * 根据date返回字符串日期
 * 
 * @param date 日期
 * @return 字符串类型日期
 */
public static String getStringDate(Date date) {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   return sdf.format(date);
}

/**
 * 根据date和格式化类型转换格式
 * 
 * @param date date
 * @param format 格式化类型
 * @return 格式类型的时间
 */
public static String getStringDate(Date date, String format) {
   SimpleDateFormat sdf = new SimpleDateFormat(format);
   return sdf.format(date);
}

/**
 * date转string
 * 
 * @param date date
 * @return string
 * @throws Exception 转换异常
 */
public static Date getDateByString(String date) throws Exception {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   return sdf.parse(date);
}

/**
 * 判断字符串是否能够转成日期类型
 * 
 * @param date 待检测字符串
 * @return 检测结果
 */
public static boolean getDateByStringExist(String date) {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   try {
      sdf.parse(date);
      return true;
   } catch (ParseException e) {
      return false;
   }
}

/**
 * 判断字符串是否能够转成日期类型
 *
 * @param date 待检测字符串
 * @return 检测结果
 */
public static boolean getDateByStringExist(String date, String format) {
   SimpleDateFormat sdf = new SimpleDateFormat(format);
   try {
      sdf.parse(date);
      return true;
   } catch (ParseException e) {
      return false;
   }
}