1:簡單的截屏——截全屏
package com.auto.Test;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class snap {
private String fileName;
private String defaultName="GuiCamera";
static int serialNum=0;
private String imageFormat;//圖像文件的格式
private String defaultImageFormat="jpg";
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
public snap(){
fileName=defaultName;
imageFormat=defaultImageFormat;
}
public snap(String s,String format) {
fileName=s;
imageFormat=format;
}
/**
* 對屏幕進行拍照
*
* **/
public void snapshot(){
try {
//拷貝屏幕到一個BufferedImage對象screenshot
BufferedImage screenshot=(new Robot()).createScreenCapture(
new Rectangle(0,0,(int)d.getWidth(),(int)d.getHeight()));
serialNum++;
//根據文件前綴變量和文件格式變量,自動生成文件名
String name=fileName+String.valueOf(serialNum)+"."+imageFormat;
System.out.println(name);
File f=new File(name);
System.out.println("Save File-"+name);
//將screenshot對象寫入圖像文件
ImageIO.write(screenshot, imageFormat, f);
System.out.println("..Finished");
} catch (Exception e) {
System.out.println(e);
}
}
/*
public static void main(String[] args) {
//"C:\\sally\\bootstrap柵格"是根據自己隨意找的一個圖片形式,"png"是圖片的格式
snap cam=new snap("C:\\sally\\bootstrap柵格","png");
cam.snapshot();
}
*/
}
2:按照指定的高度 寬度進行截屏
public class snapWithSize {
public void snap(int height,int width,String filename) {
try {
Robot robot=new Robot();
//根據指定的區域抓取屏幕的指定區域,1300是長度,800是寬度。
BufferedImage bi=robot.createScreenCapture(new Rectangle(height,width));
//把抓取到的內容寫到一個jpg文件中
ImageIO.write(bi, "jpg", new File(filename+".png"));
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3:截屏---按照指定的座標開始截屏指定高度 寬度的圖片
package CommUtils;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class snapFree {
private String fileName;
private String defaultName="GuiCamera";
static int serialNum=0;
private String imageFormat;//圖像文件的格式
private String defaultImageFormat="jpg";
public snapFree(){
fileName=defaultName;
imageFormat=defaultImageFormat;
}
public snapFree(String s,String format) {
fileName=s;
imageFormat=format;
}
/**
* 對屏幕進行拍照
*
* **/
public void snapshot(int x,int y,int width,int Height){
try {
//拷貝屏幕到一個BufferedImage對象screenshot
BufferedImage screenshot=(new Robot()).createScreenCapture(
new Rectangle(x,y,width,Height));
serialNum++;
//根據文件前綴變量和文件格式變量,自動生成文件名
String name=fileName+String.valueOf(serialNum)+"."+imageFormat;
System.out.println(name);
File f=new File(name);
System.out.println("Save File-"+name);
//將screenshot對象寫入圖像文件
ImageIO.write(screenshot, imageFormat, f);
System.out.println("..Finished");
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
//"C:\\sally\\bootstrap柵格"是根據自己隨意找的一個圖片形式,"png"是圖片的格式
snapFree cam=new snapFree("C:\\bootstrap柵格","jpg");
cam.snapshot(200,200,300,400);
}
}
4:寫入數據到txt文件
主程序
package com.auto.Test12306;
import org.junit.Test;
public class wirteContext {
private String contxt = "寫入內容";
private String path = "C:\\output.txt";
@Test
public void wirteContext() {
TestLogin testLogin = new TestLogin();
//傳入 書寫內容和路徑
testLogin.outPut(contxt,path);
}
}
寫入流
package com.auto.Test12306;
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import org.junit.Test;
public class TestLogin {
@Test
public void outPut(String wirteContext,String path) {
try {
/* 寫入Txt文件 */
File writename = new File(path); // 相對路徑,如果沒有則要建立一個新的output。txt文件
writename.createNewFile(); // 創建新文件
BufferedWriter out = new BufferedWriter(new FileWriter(writename));
out.write(wirteContext);
out.flush(); // 把緩存區內容壓入文件
out.close(); // 最後記得關閉文件
} catch (Exception e) {
e.printStackTrace();
}
}
}
5:讀取CSV文件
需要javacsv.jar包
package com.auto.lyzb.utils;
import java.nio.charset.Charset;
import java.util.ArrayList;
import com.csvreader.CsvReader;
public class ReadCSV {
public static void main(String args[])
{
ArrayList<String []> list = readCsv("C:\\Users\\Administrator\\Desktop\\test.csv");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i)[0]);//name
System.out.println(list.get(i)[1]);//age
System.out.println(list.get(i)[2]);//sex
System.out.println("-------------------");
}
}
public static ArrayList<String []> readCsv(String filePath)
{
ArrayList<String[]> list = new ArrayList<String []>();//創建保存數據集合
//創建csvreader讀取
CsvReader cReader = null;
try {
cReader = new CsvReader(filePath,',',Charset.forName("GBK"));
//是否跳過表頭
cReader.readHeaders();
//錄入數據
while(cReader.readRecord()){
list.add(cReader.getValues());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
cReader.close();
}
//如果使用testng的DataProvider,可以返回一個二維數組
Object data[][] = new Object[list.size()][];
for(int i=0;i<list.size();i++)
{
data[i]=list.get(i);
}
return list;
}
}
輸出:
QQ1
12
男
-------------------
QQ2
13
男
-------------------
QQ3
14
男
-------------------
QQ4
15
男
-------------------
QQ5
16
男
-------------------
QQ6
17
男
6:讀取excel文件內容
Maven導入jxl.jar包
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12.1</version>
</dependency>
package Auto.StreamaxTest.Case;
import java.io.File;
import jxl.*;
public class ReadExcel{
public static void main(String[] args) {
Sheet sheet = null;
Workbook book = null;
Cell cell1 = null;
try {
//hello.xls爲要讀取的excel文件名
book= Workbook.getWorkbook(new File("C:/Users/Administrator/Desktop/Auto_CSV File/AddCarGroup.xls"));
//獲得第一個工作表對象(ecxel中sheet的編號從0開始,0,1,2,3,....)
sheet=book.getSheet(0);
//獲取左上角的單元格
cell1=sheet.getCell(1,1);
System.out.println(cell1.getContents());
}
catch(Exception e) { }
}
}
7:像指定行列的excel表格中寫入指定數據
package CommUtils;
import java.io.File;
import java.util.ArrayList;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class WriteExcel {
private static ArrayList<String> arrayList;
public static void main(String[] args) {
arrayList = new ArrayList<String>();
arrayList.add("Streamax1");
arrayList.add("Streamax2");
arrayList.add("Streamax3");
WriteExcel.createExcel("c:/test.xls","第一層", 0);
}
public static void createExcel(String path,String sheetNmae,int sheetNumber) {
try {
// 在path路徑下建立一個excel文件
WritableWorkbook wbook = Workbook.createWorkbook(new File(path));
// 創建一個工作表 第一個工作區
WritableSheet wsheet = wbook.createSheet(sheetNmae, sheetNumber);
//WritableSheet wsheet1 = wbook.createSheet("數據清單2", 1);
//WritableSheet wsheet2 = wbook.createSheet("數據清單3", 2);
/**
// 設置excel裏的字體
WritableFont wf = new WritableFont(WritableFont.ARIAL, 12, WritableFont.NO_BOLD, false);
// 給標題規定字體的格式
WritableCellFormat titleFormat = new WritableCellFormat(wf);
String[] title = { "賬號", "密碼" };
// 設置表頭
for (int i = 0; i < title.length; i++) {
// 一列列的打印表頭 按照我們規定的格式
Label excelTitle = new Label(i, 0, title[i], titleFormat);
// 把標頭加到我們的工作區
wsheet.addCell(excelTitle);
}
*/
for(int i = 0;i<arrayList.size(); i++){
//向第i列 第二行寫入內容
Label lable = new Label(i, 1, arrayList.get(i));
// 把值加到工作表中
wsheet.addCell(lable);
}
// 寫入文件
wbook.write();
wbook.close();
System.out.println("創建成功!");
} catch (Exception e) {
// TODO: handle exception
}
}
}
8:寫入內容到CSV文件
需要javacsv.jar包
package streamax.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class WriteCSV {
public static void Wirtecsv(String filePath,String WirteContext) {
try {
File csv = new File(filePath); // CSV數據文件 例如:C:/Users/Administrator/Desktop/Test1/Test.csv
BufferedWriter bw = new BufferedWriter(new FileWriter(csv, true)); // 附加
// 添加新的數據行
bw.write(WirteContext);
bw.newLine();
bw.close();
} catch (FileNotFoundException e) {
// File對象的創建過程中的異常捕獲
e.printStackTrace();
} catch (IOException e) {
// BufferedWriter在關閉對象捕捉異常
e.printStackTrace();
}
}
}
9:動態WebElement
Utils函數 定位元素
package com.auto.lyzb.user;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class RegisterBean {
private WebDriver driver;
@FindBy(linkText = "用戶名")
private WebElement ele1;
@FindBy(linkText = "密碼")
private WebElement ele2;
@FindBy(linkText = "登錄")
private WebElement ele3;
//構造函數 創建對象時傳入driver
public RegisterBean(WebDriver driver) {
super();
this.driver = driver;
}
public void login(String username,String password) {
ele1.sendKeys(username);
ele2.sendKeys(password);
ele3.click();
}
}
主測試函數 用來執行登錄動作
package com.auto.lyzb.user;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class RegisterNew {
private static WebDriver driver = new FirefoxDriver();
// RegisterBean有有參構造函數
private RegisterBean rs = new RegisterBean(driver);
@Test
public void registrnew() {
driver.get("http://xx.xx.128.xx:xx端口");
rs.login("123", "qwe");
//斷言
assertEquals(true, true);
}
@AfterMethod
public void closedIE() {
driver.quit();
}
}
10:文件/文件夾的複製粘貼(本地文件夾到文件夾)
package Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.junit.Test;
public class RW {
private RW rw = new RW();
/**
*
*/
@Test
public void Test1() {
//將照片複製1000張到D:/123這個文件夾下
for (int i = 0; i < 1000; i++) {
rw.copyFile("c:/1.JPG", "D:/123/"+i+".JPG");
}
}
@Test
public void Test2() {
rw.copyFolder("D:/123", "C:/1234");
}
/***
* 複製單個文件*
*
* @param oldPath
* String 原文件路徑 如:c:/fqf.txt*
* @param newPath
* String 複製後路徑 如:f:/fqf.txt*@return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // 文件存在時
InputStream inStream = new FileInputStream(oldPath); // 讀入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字節數 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
System.out.println("複製單個文件操作出錯");
e.printStackTrace();
}
}
/**
* 複製整個文件夾內容
*
* @param oldPath
* String 原文件路徑 如:c:/fqf
* @param newPath
* String 複製後路徑 如:f:/fqf/ff
* @return boolean
*/
public void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); // 如果文件夾不存在 則建立新文件夾
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夾
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("複製整個文件夾內容操作出錯");
e.printStackTrace();
}
}
}
11:文件的複製粘貼(本地文件夾到ftp路徑)
commons-net-3.6.jar包
package Test1;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.testng.annotations.Test;
public class ftpUpload {
@Test
public void testFtpClient(){
//創建一個FTPClient對象
FTPClient ftpClient = new FTPClient();
//創建FTP連接,端口號可以設定,我的是22,默認是21
try {
ftpClient.connect("xxx.xxx.151.47",21);
//登錄FTP服務器,使用用戶名和密碼 下列寫法是沒有密碼的寫法
ftpClient.login("anonymous", "");
//ftpClient.enterRemotePassiveMode();
//ftpClient.setControlEncoding("gb18030");
//上傳文件,讀取本地文件
String path = "C:/1.jpg";
FileInputStream inputStream = new FileInputStream(new File(path));
//設置上傳的路徑
String pathname = "/abc";//這個路徑就是FTP服務端存儲的路徑,先要確保abc這個文件目錄存在
ftpClient.changeWorkingDirectory(pathname); //保證上傳到指定的目錄下 如果沒有這一句 將會上傳到ftp根目錄下
//參數一:服務器端文檔名;參數二:上傳文檔的inputStream
String remote = "1.jpg";
ftpClient.storeFile(remote, inputStream);
//關閉連接
ftpClient.logout();
} catch (Exception e) {
e.printStackTrace();
}
}
}
12:讀取一個文件夾下所有文件的文件名稱全稱(包括後綴名)
package streamax.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ReadFileNanes {
//文件名列表
private static List<String> fileList = new ArrayList<String>();
/**
* @param args
*/
public static void main(String[] args) {
//該目錄下有123.jpg 和 20180515153634_10.jpg兩文件
printAllFileNames("C:/Users/Administrator/Desktop/Test1");
}
public static void printAllFileNames(String path) {
if (null != path) {
File file = new File(path);
if (file.exists()) {
File[] list = file.listFiles();
if(null != list){
for (File child : list) {
if (child.isFile()) {
fileList.add(child.getAbsolutePath());
String filePath = child.getAbsolutePath();
String jieguo = filePath.substring(filePath.indexOf("Test1")+6,filePath.indexOf(".jpg")+4);
System.out.println(jieguo);
//輸出內容爲
// 123.jpg
// 20180515153634_10.jpg
// System.out.println("==============");
} else if (child.isDirectory()) {
printAllFileNames(child.getAbsolutePath());
}
}
}
}
}
}
}
13:截屏---按照指定的座標截取指定尺寸大小的圖片
package CommUtils;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class snapFree {
// ===源圖片路徑名稱如:c:\1.jpg
private String srcpath;
// ===剪切圖片存放路徑名稱.如:c:\2.jpg
private String subpath;
// ===剪切點x座標
private int x;
private int y;
// ===剪切點寬度
private int width;
private int height;
public snapFree() {
}
public snapFree(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* 對圖片裁剪,並把裁剪完蛋新圖片保存 。
*/
public void cut() throws IOException {
FileInputStream is = null;
ImageInputStream iis = null;
try {
// 讀取圖片文件
is = new FileInputStream(srcpath);
/*
* 返回包含所有當前已註冊 ImageReader 的 Iterator,這些 ImageReader 聲稱能夠解碼指定格式。
* 參數:formatName - 包含非正式格式名稱 . (例如 "jpeg" 或 "tiff")等 。
*/
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = it.next();
// 獲取圖片流
iis = ImageIO.createImageInputStream(is);
/*
* <p>iis:讀取源.true:只向前搜索 </p>.將它標記爲 ‘只向前搜索’。
* 此設置意味着包含在輸入源中的圖像將只按順序讀取,可能允許 reader 避免緩存包含與以前已經讀取的圖像關聯的數據的那些輸入部分。
*/
reader.setInput(iis, true);
/*
* <p>描述如何對流進行解碼的類<p>.用於指定如何在輸入時從 Java Image I/O
* 框架的上下文中的流轉換一幅圖像或一組圖像。用於特定圖像格式的插件 將從其 ImageReader 實現的
* getDefaultReadParam 方法中返回 ImageReadParam 的實例。
*/
ImageReadParam param = reader.getDefaultReadParam();
/*
* 圖片裁剪區域。Rectangle 指定了座標空間中的一個區域,通過 Rectangle 對象
* 的左上頂點的座標(x,y)、寬度和高度可以定義這個區域。
*/
Rectangle rect = new Rectangle(x, y, width, height);
// 提供一個 BufferedImage,將其用作解碼像素數據的目標。
param.setSourceRegion(rect);
/*
* 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對象,並將 它作爲一個完整的
* BufferedImage 返回。
*/
BufferedImage bi = reader.read(0, param);
// 保存新圖片
ImageIO.write(bi, "jpg", new File(subpath));
} finally {
if (is != null)
is.close();
if (iis != null)
iis.close();
}
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getSrcpath() {
return srcpath;
}
public void setSrcpath(String srcpath) {
this.srcpath = srcpath;
}
public String getSubpath() {
return subpath;
}
public void setSubpath(String subpath) {
this.subpath = subpath;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public static void main(String[] args) {
snapFree operateImage = new snapFree(469, 222, 100, 100);//開始的寬度,開始的高度,截圖寬度,截圖高度
operateImage.srcpath = "C:/Users/Administrator/Desktop/1.jpg";
operateImage.subpath = "C:/Users/Administrator/Desktop/2.jpg";
try {
operateImage.cut();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.14 確定/取消對話框執行對應操作
package enter.entrys;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.junit.Test;
public class demo {
@Test
public void test(){
int n = JOptionPane.showConfirmDialog(null, "確認刪除嗎?", "確認對話框", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
// JOptionPane.showMessageDialog(new JFrame(),"已刪除");
System.out.println("執行確定的操作");
} else if (n == JOptionPane.NO_OPTION) {
// JOptionPane.showMessageDialog(new JFrame(),"已取消");
System.out.println("執行取消的操作");
}
}
}