public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ArrayList<String> list = new ArrayList<>();
list.add("oiuoaisduf");
list.add("asljkdf");
Class<? extends ArrayList> aClass1 = list.getClass(); //通过对象名获取class
Class<ArrayList> aClass2 = ArrayList.class; //通过集合获取class
Class<?> aClass3 = Class.forName("java.util.ArrayList"); //通过包和类名获取class
Method add = aClass1.getDeclaredMethod("add", Object.class);
add.invoke(list,5.21345689756);
add.invoke(list,123456789);
add.invoke(list,5.21345689756);
System.out.println(list);
}
private static HashMap<String,User> map = new HashMap<>();
static {
User no1 = new User("wangyide", "5210");
User no2 = new User("aaa", "123");
map.put("user1",no1);
map.put("user2",no2);
}
public static void main(String[] args) {
Class<HashMap> hashMapClass = HashMap.class;
Collection<User> values = map.values();
Field[] declaredFields = hashMapClass.getDeclaredFields();
}
public class Demo {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
start();
}
private static void start() throws Exception {
System.out.println("1.文件目录操作");
System.out.println("0.退出");
System.out.println("请输入您的选择:");
switch (scanner.nextInt())
{
case 1:
System.out.println("1:D:\\ 2.C:\\");
System.out.println("请选择路径");
File file = new File("D:\\");
File file1 = new File("C:\\");
if (scanner.nextInt()==2)
{
show(file1);
}else {
show(file);
}
start();
break;
case 0:
System.out.println("谢谢使用");
System.exit(0);
break;
default:
System.out.println("输入错误,请重新输入");
start();
break;
}
}
private static void show(File file1) throws Exception {
if (file1.isDirectory())
{
File[] files = file1.listFiles();
for (File s:
files) {
System.out.println(s.getName());
}
System.out.println("1.继续打开 2.创建文件 3.创建文件夹 4.删除文件或文件夹 5.返回上一级 0.退出");
int i = scanner.nextInt();
if (i==1)
{
System.out.println("请输入文件名:");
String name = scanner.next();
for (File s:
files) {
if (name.equals(s.getName()))
{
show(s);
}
}
}else if (i==2)
{
System.out.println("请输入文件名(加后缀名如:.txt):");
String name = scanner.next();
File file = new File(file1+"/"+name);
file.createNewFile();
}else if (i==3)
{
System.out.println("请输入文件夹名:");
String name = scanner.next();
File file = new File(file1+"/"+name);
file.mkdir();
}else if (i==4)
{
System.out.println("请输入要删除的文件夹:");
String name = scanner.next();
File file6 = new File(file1+"/"+name);
deleteFile(file6);
System.out.println("删除成功");
}else if (i==0)
{
System.exit(0);
}else if (i==5)
{
String path = file1.getPath();
File parentFile = file1.getParentFile();
show(parentFile);
}
else {
System.out.println("输入错误");
}
}
}
private static void deleteFile(File file) {
if (file.exists())
{
if (file.isFile())
{
file.delete();
}else {
if (file.length()==0)
{
file.delete();
}
File[] files = file.listFiles();
for (File f:
files) {
if (f.isFile())
{
f.delete();
}else {
deleteFile(f);
}
}
file.delete();
}
}else {
System.out.println("不存在此文件");
}
}
}
缓冲流
缓冲流是用来优化字节或字符流的,
一般字符流比字节流读写要快,但字节流可读取写入除字符以外的数据
序列化流
序列化流可以读取或写入对象,但直接写入会造成乱码
转换流
转换流用来将字节流和字符流相互替换
一般读取JSON-url中的数据获取的流为字节流
一般编程会把字节流转换为字符流
加上缓冲流达到最佳效果
FileInputStream fileInputStream = new FileInputStream("字节流.txt");
byte[] bs = new byte[1024]; //用来存 读到的内容
int len = fileInputStream.read(bs); //len:读到的长度
String string = new String(bs,0,len);
System.out.println(string);
fileInputStream.close();
FileOutputStream fileOutputStream = new FileOutputStream("字节流.txt");
fileOutputStream.write("你好".getBytes());
fileOutputStream.close();
FileReader fileReader = new FileReader("字符流.txt");
char[] cs = new char[1024]; //保存读到的内容
int len = fileReader.read(cs);
String string = new String(cs,0,len);
System.out.println(string);
fileReader.close();
FileWriter fileWriter = new FileWriter("字符流.txt");
fileWriter.write("你好");
fileWriter.close();
//读
FileInputStream fileInputStream = new FileInputStream("D:\\install\\ideaIU-2020.1.3.exe");
//写
FileOutputStream fileOutputStream = new FileOutputStream("D:/aaa.exe");
byte[] bs = new byte[1024]; //存储读取到的内容
while (true) {
int len = fileInputStream.read(bs);
if (len==-1) {
break;
}
fileOutputStream.write(bs, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
FileWriter fileWriter = new FileWriter("缓冲字符流.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("缓冲字符流,你好");
bufferedWriter.close();
FileReader fileReader = new FileReader("缓冲字符流.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
// char[] cs = new char[1024];
//
// int len = bufferedReader.read(cs);
//
// String string = new String(cs, 0, len);
// System.out.println(string);
//特有的方法 读一行
// String readLine = bufferedReader.readLine();
// System.out.println(readLine);
//一般使用方法
String s = "";
StringBuffer stringbuffer = new StringBuffer();
while((s = bufferedReader.readLine())!=null){
stringbuffer.append(s);
}
System.out.println(stringbuffer.toString());
bufferedReader.close();
//写
FileOutputStream fileOutputStream = new FileOutputStream("转换流.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream , "UTF-8");
outputStreamWriter.write("转换流你好");
outputStreamWriter.close();
//读
FileInputStream fileInputStream = new FileInputStream("转换流.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
char[] cs = new char[1024];
int len = inputStreamReader.read(cs);
String string = new String(cs, 0, len);
System.out.println(string);
inputStreamReader.close();
FileInputStream fileInputStream = new FileInputStream("序列化流.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Student readObject = (Student) objectInputStream.readObject();
System.out.println(readObject);
objectInputStream.close();
FileOutputStream fileOutputStream = new FileOutputStream("序列化流.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
Student student = new Student("张三");
objectOutputStream.writeObject(student);
objectOutputStream.close();
简单群聊系统
服务类,用于循环获取客户端的连接,并创建每个连接客户端伴生的服务子线程类
public class Server {
//list用于存储连接中的Socket(存储在线好友)一般用HashMap存储
//再使用list存储User类
private static ArrayList<Socket> list = new ArrayList<>();
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(37618);
System.out.println("等待连接中...........");
int i=0;
while (true)
{
Socket accept = serverSocket.accept();
list.add(accept);
System.out.println("连接成功");
new ServerThread(list,accept,i).start();
}
}
}
public class ServerThread extends Thread{
private ArrayList<Socket> arrayList;
private Socket socket;
private int i;
public ServerThread(ArrayList<Socket> arrayList, Socket socket, int i) {
this.arrayList = arrayList;
this.socket = socket;
this.i = i;
}
@Override
public void run() {
while (true)
{
try {
InputStream inputStream = socket.getInputStream();
byte[] bs = new byte[1024];
int len = inputStream.read(bs);
String s = new String(bs, 0, len);
s=getId()+":"+s;
for (Socket s1:
arrayList) {
OutputStream outputStream = s1.getOutputStream();
outputStream.write(s.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端类用来循环提示输入消息,并且发送至服务层
public class Client {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",37618);
new ClientThread(socket).start(); //循环接收消息
System.out.println("请输入你要群发的消息:");
while (true)
{
String next = scanner.next();
OutputStream outputStream = socket.getOutputStream();
outputStream.write(next.getBytes());
}
}
}
客户端子线程类用来循环接收消息,并显示到控制台
public class ClientThread extends Thread{
private Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
while (true){
try {
InputStream inputStream = socket.getInputStream();
byte[] bs = new byte[1024];
int len = inputStream.read(bs);
String s = new String(bs, 0, len);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
所有控件的父类,中文翻译为视图
有着基础属性,例如background等
用于包裹RadioButton的控件
radioButton在选择时,需要实现单选,这是就用到了RadioGroup
单选按钮 一般需要RadioGroup嵌套
android:text=“设置单选按钮后的文字”
多选框控件,可以不用RadioGroup嵌套,
其余属性和RadioButton类似
继承于TextView
按钮控件 android:text=“用于设置文字”
android:onClick=“设置点击事件方法名”
写完后(alt+enter)选择create会在java中创建点击事件
继承于View
按钮控件 android:text=“用于设置文字”,可设置点击事件,
textSize用于设置字体大小,textColor设置颜色等
继承于View
显示图片控件,android:src="设置图片位置"
小技巧:将宽和高其一设置为固定值,另一个设置为wrap_content可防止图片扭曲
继承于ImageView
用法与ImageView类似
可进行垂直滚动的控件,但其中仅可设置一个布局控件,
当内容溢出 即可垂直滑动
顾名知义,水平滚动控件,简介同上
继承于TextView
输入文本框控件,android:hint=“可用于设置提示文本”
可以以列表形式展现的控件,需要设置适配器,或者使用静态item,仅可使用一列
可以使用多列的ListView
系统menu会在header的右侧显示最小化菜单栏.
必要因素onCreateOptionMenu创建时
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.item,menu);
return super.onCreateOptionsMenu(menu);
}
必要因素onOptionsItemSelected点击时
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.option_one:
break;
case R.id.option_two:
break;
case R.id.option_three:
break;
}
return super.onOptionsItemSelected(item);
}
ContextMenu需要绑定控件,并长按绑定空控件显示ContextMenu
必要因素onCreateContextMenu
//加载布局
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.menu2, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
必要因素onContextItemSelected
//监听事件
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.hong:
tv1.setTextColor(Color.parseColor("#ff0000"));
break;
case R.id.lv:
break;
case R.id.lan:
break;
}
return super.onContextItemSelected(item);
}
对比ContextMenu长按绑定控件显示来说,自定义Menu只需要单击绑定控件即可显示
使用比ContextMenu要灵活
public void tv1(View view) {
PopupMenu popupMenu = new PopupMenu(this,view);
popupMenu.inflate(R.menu.menu2);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.hong:
tv2.setTextColor(Color.parseColor("#ff0000"));
break;
case R.id.lv:
tv2.setTextColor(Color.parseColor("#00ff00"));
break;
case R.id.lan:
tv2.setTextColor(Color.parseColor("#0000ff"));
break;
}
return false;
}
});
}
弹出对话框
普通对话框可以编写Message,编写icon(图标),编写title等
/**
* 普通对话框
* @param view
*/
public void btn1(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon);
builder.setTitle("删除");
builder.setMessage("您确定要删除此消息");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
顾名知义,单选对话框就是有着radio控件的对话框
/**
* 单选对话框
* @param view
*/
public void btn2(View view) {
final int[] click = new int[1];
final String[] data = new String[]{
"足球","篮球","唱歌","台球"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon);
builder.setTitle("单选");
builder.setSingleChoiceItems(data, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
click[0] = which;
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, data[click[0]].toString(), Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
顾名思义
//多选对话框
public void tion3(View view) {
//构建者
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//设置属性
builder.setIcon(R.drawable.ic_launcher_background);
builder.setTitle("她们");
final String[] strings = {
"小晓", "小齐", "小琳", "晓丽"};
boolean[] booleans = {
true,true,false,false};
//参数 Sing数组 boolean数组 监听事件
builder.setMultiChoiceItems(strings, booleans, new DialogInterface.OnMultiChoiceClickListener() {
//多选内容
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
}
});
//创建
AlertDialog alertDialog = builder.create();
//显示
alertDialog.show();
}
进度条对话框显示进度 一般用于加载数据中使用
/**
* 进度条对话框
* @param view
*/
public void btn3(View view) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMax(100);
progressDialog.setTitle("进度条对话框");
progressDialog.setIcon(R.drawable.icon);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
//Timer用于加载进度条 类似于一种循环
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
int i = 0;
@Override
public void run() {
if (i==progressDialog.getMax()){
timer.cancel();
progressDialog.dismiss();
}
progressDialog.setProgress(i+=1);
}
},0,50);
}
自定义对话框类似于普通builder,只不过将原先的setMessage改为setView
/**
* 自定义对话框
* @param view
*/
public void btn4(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("自定义对话框");
builder.setIcon(R.drawable.icon);
View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.menu, null);
builder.setView(inflate);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
inflate.findViewById(R.id.btn_yes).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
inflate.findViewById(R.id.btn_no).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
}
PopupWindow使用比PopupMenu更加灵活,可以设置弹出位置
public void btn1(View view) {
PopupWindow popupWindow = new PopupWindow();
//宽高必须要有
popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//点击外部取消
popupWindow.setOutsideTouchable(true);
//遮罩效果
//WindowManager.LayoutParams attributes = getWindow().getAttributes();
//attributes.alpha = 0.5f;
//getWindow().setAttributes(attributes);
//恢复透明度
//popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
// @Override
// public void onDismiss() {
// WindowManager.LayoutParams attributes = getWindow().getAttributes();
// attributes.alpha = 1.0f;
// getWindow().setAttributes(attributes);
// }
//});
//加载布局
View inflate = LayoutInflater.from(this).inflate(R.layout.popu, null);
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
popupWindow.setContentView(inflate);//设置布局
View activity_main = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
//在activity_main布局的最下边
popupWindow.showAtLocation(activity_main, Gravity.BOTTOM,0,0);
//显示到某个控件的下边
//popupWindow.showAsDropDown(add);
//设置入场动画
//popupWindow.setAnimationStyle(R.style.popuoo);
//控件里的点击事件
inflate.findViewById(R.id.sao).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "hhhhhhh", Toast.LENGTH_SHORT).show();
}
});
}
简化版
public void btn1(View view) {
PopupMenu popupMenu = new PopupMenu(this,view);
PopupWindow popupWindow = new PopupWindow();
popupWindow.setWidth(300);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setOutsideTouchable(true);
View inflate1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.menu, null);
popupWindow.setContentView(inflate1);
View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
// popupWindow.showAtLocation(inflate, Gravity.RIGHT,0,-500);
RelativeLayout relativeLayout = findViewById(R.id.title);
popupWindow.showAsDropDown(relativeLayout,9999,0);
}
public void btn1(View view) {
//构造者
Notification.Builder builder = new Notification.Builder(this);
//小图标(必须设置,不然报错)
builder.setSmallIcon(R.drawable.ic_launcher_background);
//加载布局
RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.notification);
//设置文字
//remoteViews.setTextViewText(R.id.text_id,"设置文字");
//设置图片
//remoteViews.setImageViewResource(R.id.img_id,R.drawable.ic_launcher_background);
//设置自定义布局
builder.setCustomContentView(remoteViews);
// Big
//builder.setCustomBigContentView(remoteViews);
//发通知
NotificationManager systemService = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
systemService.notify(1,builder.build());
}
fragment配合RadioGroup和RadioButton可以实现 购物软件下方导航
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BlankFragment1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="111111111111111111111111111111"/>
</FrameLayout>
public class BlankFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank_fragment1, container, false);
}
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//利用switch来切换不同的UI片段
switch (checkedId){
case R.id.index:
//管理者对象(片段管理器)
FragmentManager manager = getSupportFragmentManager();
//开启事务
FragmentTransaction fragmentTransaction = manager.beginTransaction();
//添加fragment
Index index = new Index();
//替换片段
//其中R.id.ll是Main布局中的片段容器,
//index是Fragment
//另外add是添加,replace是替换
//fragmentTransaction.add(R.id.ll,index);
fragmentTransaction.replace(R.id.ll, index);
//提交事务
fragmentTransaction.commit();
break;
}
}
});