我做了这个程序,它使用机器人类和bufferedimage类获取截图。包含屏幕截图的.png文件将保存到存在.java文件的文件夹中。我希望将图像文件写入我创建的另一个名为screenshot的文件夹中。我尝试重命名文件,也尝试使用inputstream和outputstream类进行复制,但结果相同。我怎么能克服这个?我使用的是Windows 8和java 1.8.0
package screenshot;
//Packages imported for the program
import java.io.*;
import java.nio.file.*;
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;
import java.util.*;
import java.text.*;
//Class logic written beside each statement
public class Screenshot
{
public static void main(String[] args)
{
try
{ //Exception Handling
SimpleDateFormat df=new SimpleDateFormat("dd-MM-yy H-m'.png'"); //Setting the date format
Date date=new Date(); //Getting the current date and time
String ref=df.format(date); //Formatting the current date in the SDF constructor's format
//String dirname="M:\\Java\\bin\\screenshot\\";
System.out.println(ref); //Testing whether the current date is getting displayed in the desired format
Robot robot = new Robot(); //Instanciating the Robot class
Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); //Declaring a rectangle with size of the screen
BufferedImage bufferedImage = robot.createScreenCapture(captureSize); //Capturing the screenshot and save it in Buffered image object
//File dir = new File(dirname);
//File filen = new File("M:\\Java\\bin\\screenshot\\temp.png");
File filename = new File(ref);
ImageIO.write(bufferedImage, "png" , filename); //writing the image to a file called filename
}
catch(Exception e)
{
System.err.println(e); //Exception message display
}
}
}
答案 0 :(得分:0)
将文件存储到文件夹screenshot
,更改变量
String ref=df.format(date);
到
String ref = "absolute_path_of_folder/" + df.format(date); // like "C:/screenshot/" + df.format(date);
它会将文件保存到该文件夹。
答案 1 :(得分:0)
File
的双参数构造函数,它使用表示目录的File
和该目录中文件的名称。我取消注释了描述要保存到哪个目录的行,并使用了该目录。
SimpleDateFormat df=new SimpleDateFormat("dd-MM-yy H-m'.png'"); //Setting the date format
Date date=new Date(); //Getting the current date and time
String ref=df.format(date); //Formatting the current date in the SDF constructor's format
String dirname="M:\\Java\\bin\\screenshot\\";
System.out.println(ref); //Testing whether the current date is getting displayed in the desired format
Robot robot = new Robot(); //Instanciating the Robot class
Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); //Declaring a rectangle with size of the screen
BufferedImage bufferedImage = robot.createScreenCapture(captureSize); //Capturing the screenshot and save it in Buffered image object
File dir = new File(dirname);
File filen = new File("M:\\Java\\bin\\screenshot\\temp.png");
File filename = new File(filen, ref);
ImageIO.write(bufferedImage, "png" , filename); //writing the image to a file called filename
答案 2 :(得分:0)
包名称与目标文件夹的名称相同。更改包名称或文件夹名称,列出的每个方法都正常工作