FileInputStream
fis
=
new
FileInputStream("D:/test.pdf")//要进行复制的文件读取
FileOutputStream
fos
=
new
FileOutputStream("D:/testFinal.pdf")//要保存的文件
int
length
=
0//初始化流长度
byte[]
buffer
=
new
byte[2024]
//
缓存字节设置为2m
while((length=fis.read(buffer))
!=
-1){//如果内容长度不是空
fos.write(buffer,
0,
length)//写入到新文件
}
fos.close()//关闭不用的流
fis.close()//关闭不需要的流
备注:IO流在使用完成后,一定要通过close方法及时关闭。
import java.io.Fileimport java.io.FileOutputStreamimport java.io.OutputStreamWriterimport java.io.Writerimport java.net.MalformedURLExceptionimport java.net.URLimport org.pdfbox.pdmodel.PDDocumentimport org.pdfbox.util.PDFTextStripperpublic class PdfReader {public void readFdf(String file) throws Exception {// 是否排序boolean sort = false// pdf文件名String pdfFile = file// 输入文本文件名称String textFile = null// 编码方式String encoding = "UTF-8"// 开始提取页数int startPage = 1// 结束提取页数int endPage = Integer.MAX_VALUE// 文件输入流,生成文本文件Writer output = null// 内存中存储的PDF DocumentPDDocument document = nulltry {try {// 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件URL url = new URL(pdfFile)//注意参数已不是以前版本中的URL.而是File。document = PDDocument.load(pdfFile)// 获取PDF的文件名String fileName = url.getFile()// 以原来PDF的名称来命名新产生的txt文件if (fileName.length() >4) {File outputFile = new File(fileName.substring(0, fileName.length() - 4)+ ".txt")textFile = outputFile.getName()}} catch (MalformedURLException e) {// 如果作为URL装载得到异常则从文件系统装载//注意参数已不是以前版本中的URL.而是File。document = PDDocument.load(pdfFile)if (pdfFile.length() >4) {textFile = pdfFile.substring(0, pdfFile.length() - 4)+ ".txt"}}// 文件输入流,写入文件倒textFileoutput = new OutputStreamWriter(new FileOutputStream(textFile),encoding)// PDFTextStripper来提取文本PDFTextStripper stripper = nullstripper = new PDFTextStripper()// 设置是否排序stripper.setSortByPosition(sort)// 设置起始页stripper.setStartPage(startPage)// 设置结束页stripper.setEndPage(endPage)// 调用PDFTextStripper的writeText提取并输出文本stripper.writeText(document, output)} finally {if (output != null) {// 关闭输出流output.close()}if (document != null) {// 关闭PDF Documentdocument.close()}}}/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubPdfReader pdfReader = new PdfReader()try {// 取得E盘下的SpringGuide.pdf的内容pdfReader.readFdf("E://SpringGuide.pdf")} catch (Exception e) {e.printStackTrace()}}}题主问的是java文件流读取pdf文件读到一半返回-1是什么意思?达到了流的结尾。返回-1是到达的意思,java文件流读取pdf文件读到一半返回-1意味着已经达到了流的结尾,因此在该流中没有更多内容可以阅读,需要重新打开。
java是一种计算机编程语言,拥有跨平台,面向对象,泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发,任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言。