首先肯定是要判断该文件名到底存不存在:
我们定义一个方法:用来判断是否存在该文件,如果存在,获取父路径并拼接用来创建文件,如果不存在则打印“你输入的文件不存在”
- private static File createFile(String fileName) throws IOException {
- File file = new File(fileName);
- if (file.exists()) {
- //获取父路径并拼接
- File copyFile = new File(file.getParent() + "/copy_" + file.getName());
- //复制后的路径
- System.out.println(copyFile);
- //创建文件
- copyFile.createNewFile();
- //返回创建的文件
- return copyFile;
- } else {
- System.out.println("你输入的文件不存在");
- }
- return null;
- }
- }
文件创建完成后,进行传输文件内容工作:
判断是否创建完成,我这里用是否为空来判断:
文件传输我这里没有解决异常(try...catch)而是选择抛异常的方式:
- private static boolean copyFile(String fileName) throws IOException {
- File copyFile = createFile(fileName);
- //判断拷贝是否为空
- if (copyFile == null) {
- return false;
- }
- InputStream inputStream = new FileInputStream(fileName);//读源文件
- OutputStream outputStream = new FileOutputStream(copyFile);//写到复制出的文件中
- int len = 0;
- while ((len = inputStream.read()) != -1) {
- outputStream.write(len);
- }
- inputStream.close();
- outputStream.close();
- return true;
- }
主方法:
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一个文件名:");
- String fileName = "C:/summerjava/" + sc.next();
- boolean flag = false;
- try {
- flag = copyFile(fileName);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- System.out.println(flag);//创建成功
- }


随机生成百位以内数字:
int ran=new Random().nextInt(100)
- List<Integer> list = new ArrayList<>();
- for (int i = 0; i <10 ; i++) {
- list.add(new Random().nextInt(100));
- }//生成的10个随机数字,并存入到集合中
- System.out.println("随机生成的:"+list);
- for (int i = 0; i <list.size() ; i++) {
- for (int j = i; j <list.size() ; j++) {
- if(list.get(i)>=list.get(j)){
- int temp=list.get(i);
- list.set(i,list.get(j));
- list.set(j,temp);
- }
- }
- }
- System.out.println("排序后"+list);

我首先定义一个方法用来生成十位随机字符串:
- public static String random(){
- String chars = "qwertyuioplkjhgfdsazxcvbnm0123456789QWERTYUIOPLKJHGFDSAZXCVBNM";
- StringBuffer value = new StringBuffer();
- for (int i = 0; i < 10; i++) {
- value.append(chars.charAt((int)(Math.random() * 62)));
- }
- return value.toString();
- }
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一个字符串");
- String str = sc.next();
- Boolean flag = false;
- String [] arr =new String[100];
- for (int i = 0; i <arr.length ; i++) {
- arr[i]=random();
- if(str==arr[i]){
- flag=true;
- }
- //System.out.println(arr[i]);//可以打印看看字符串都有什么
- }
- System.out.println("您输入的字符串:"+str+(flag?"在":"不在")+"随机生成的字符中");
