java 在eclipse工程下读取文件内容和打成war包后,读取同样文件内容,正确读取

java 在eclipse工程下读取文件内容和打成war包后,读取同样文件内容,正确读取,第1张

首先war打完之后你可以用解压软件看看里面的文件结构,和工程是不一样的。没有src/main/这一层。因此如果要满足你的使用相对路径要求,又要通用,只有两个方法

1、在项目下重新建一个resource资源包,配置文件放在里面,然后根据resource相对路径读取

2、变更项目打包结构,打包输出时把src/main/这层加上

总之这两个方法的目的都是为了让war包结构和你工程一致。

我的读取配置文件方法如下,你可以参考下。文件路径:

        String path = null

        try {

            path = SellerProductController.class.getClassLoader()

                    .getResource("").toURI().getPath()

            log.info("获取到配置文件的路径为:" + path)

        } catch (URISyntaxException e) {

            log.error("获取配置文件路径出现异常," + e.getMessage())

        }

        // 把文件读入文件输入流,存入内存中

        FileInputStream fis = null

        try {

            fis = new FileInputStream(new File(path + "isa_addr.json"))

        } catch (FileNotFoundException e) {

            log.error("读取配置文件出现异常," + e.getMessage())

        }

        // 设置response的字符集为项目指定字符集

        response.setCharacterEncoding("UTF-8")

        // 创建输出流对象

        PrintWriter out = null

        try {

            out = response.getWriter()

        } catch (IOException e) {

            log.error("创建输出流对象失败:" + e.getMessage())

        }

        String res = this.ReadFile(fis)

        log.debug("最终获得的Json串为:" + res)

java有专门 *** 作CSV文件的类和方法。java开源框架csvreader提供了一个轻量级的、简单方便的统一 *** 作接口可用。要使用CsvReader,CsvWriter需要下载一个javacsv.jar导入到项目中才行,在项目上点击右键--属性--库--添加jar文件,选择javacsv.jar文件即可,然后在程序中用import

com.csvreader.CsvReader,import com.csvreader.CsvWriter导入即可。

示范代码:

package test

import com.csvreader.CsvReader

import com.csvreader.CsvWriter

import java.io.BufferedReader

import java.io.BufferedWriter

import java.io.File

import java.io.FileNotFoundException

import java.io.FileReader

import java.io.FileWriter

import java.io.IOException

public class readandwrite {

public static void main(String[] args) throws IOException {

String [] str = {"省","市","区","街","路","里","幢","村","室","园","苑","巷","号"}

String inString = ""

String tmpString = ""

File inFile = new File("C://in.csv")// 读取的CSV文件

File outFile = new File("C://outtest.csv")//输出的CSV文

try {

BufferedReader reader = new BufferedReader(new FileReader(inFile))

BufferedWriter writer = new BufferedWriter(new FileWriter(outFile))

CsvReader creader = new CsvReader(reader, ',')

CsvWriter cwriter = new CsvWriter(writer,',')

while(creader.readRecord()){

inString = creader.getRawRecord()//读取一行数据

for(int i = 0i <str.lengthi++){

tmpString = inString.replace(str[i], "," + str[i] + ",")

inString = tmpString

}

//第一个参数表示要写入的字符串数组,每一个元素占一个单元格,第二个参数为true时表示写完数据后自动换行

cwriter.writeRecord(inString.split(","), true)

//注意,此时再用cwriter.write(inString)方法写入数据将会看到只往第一个单元格写入了数据,“,”没起到调到下一个单元格的作用

//如果用cwriter.write(String str)方法来写数据,则要用cwriter.endRecord()方法来实现换行

//cwriter.endRecord()//换行

cwriter.flush()//刷新数据

}

creader.close()

cwriter.close()

} catch (FileNotFoundException ex) {

ex.printStackTrace()

}

}

}

java中读取ppt的实现方法如下:

public class ReadFileUtils {

/**

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

ReadFileUtils rf = new ReadFileUtils()

String s = ""

// s = rf.readTXT("E:/itsm文档的后缀名分析报告2.txt")

// s = rf.readPDF("E:/memcached全面剖析.pdf")

// s = rf.readEXCEL("E:/副本工作量及成本模板.xls")

// s = rf.readEXCEL2007("E:/功能点估算方案.xlsx")

// s = rf.readWORD("E:/pms中文.doc")

// s = rf.readWORD2007("E:/功能点估算方法.docx")

//s = rf.readPPT("E:/精细化管理信息系统项目汇报v1.0.ppt")

s = rf.readPPT2007("e:/精细化管理信息系统项目汇报v1.0.pptx")

System.out.println(s)

}

// 读取ppt

public String readPPT(String file) throws IOException {

StringBuilder sb = new StringBuilder()

SlideShow ppt = new SlideShow(new HSLFSlideShow(file))

Slide[] slides = ppt.getSlides()

//提取文本信息

for (Slide each : slides) {

TextRun[] textRuns = each.getTextRuns()

for (int i=0 i<textRuns.lengthi++ ) {

RichTextRun[] richTextRuns = textRuns.getRichTextRuns()

for (int j = 0j <richTextRuns.lengthj++) {

sb.append(richTextRuns[j].getText())

}

sb.append("\n")

}

sb.append("\n")

}

return sb.toString()

}

// 读取pptx

public String readPPT2007(String file) throws IOException, XmlException, OpenXML4JException {

return new XSLFPowerPointExtractor(POIXMLDocument.openPackage(file)).getText()

}

// 读取xls文件

public String readEXCEL(String file) throws IOException {

StringBuilder content = new StringBuilder()

HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file))// 创建对Excel工作簿文件的引用

for (int numSheets = 0numSheets <workbook.getNumberOfSheets()numSheets++) {

if (null != workbook.getSheetAt(numSheets)) {

HSSFSheet aSheet = workbook.getSheetAt(numSheets)// 获得一个sheet

for (int rowNumOfSheet = 0rowNumOfSheet <= aSheet

.getLastRowNum()rowNumOfSheet++) {

if (null != aSheet.getRow(rowNumOfSheet)) {

HSSFRow aRow = aSheet.getRow(rowNumOfSheet)// 获得一个行

for (short cellNumOfRow = 0cellNumOfRow <= aRow

.getLastCellNum()cellNumOfRow++) {

if (null != aRow.getCell(cellNumOfRow)) {

HSSFCell aCell = aRow.getCell(cellNumOfRow)// 获得列值

if (this.convertCell(aCell).length() >0) {

content.append(this.convertCell(aCell))

}

}

content.append("\n")

}

}

}

}

}

return content.toString()

}

// 读取xlsx文件

public String readEXCEL2007(String file) throws IOException {

StringBuilder content = new StringBuilder()

XSSFWorkbook workbook = new XSSFWorkbook(file)

for (int numSheets = 0numSheets <workbook.getNumberOfSheets()numSheets++) {

if (null != workbook.getSheetAt(numSheets)) {

XSSFSheet aSheet = workbook.getSheetAt(numSheets)// 获得一个sheet

for (int rowNumOfSheet = 0rowNumOfSheet <= aSheet

.getLastRowNum()rowNumOfSheet++) {

if (null != aSheet.getRow(rowNumOfSheet)) {

XSSFRow aRow = aSheet.getRow(rowNumOfSheet)// 获得一个行

for (short cellNumOfRow = 0cellNumOfRow <= aRow

.getLastCellNum()cellNumOfRow++) {

if (null != aRow.getCell(cellNumOfRow)) {

XSSFCell aCell = aRow.getCell(cellNumOfRow)// 获得列值

if (this.convertCell(aCell).length() >0) {

content.append(this.convertCell(aCell))

}

}

content.append("\n")

}

}

}

}

}

return content.toString()

}

private String convertCell(Cell cell) {

NumberFormat formater = NumberFormat.getInstance()

formater.setGroupingUsed(false)

String cellValue = ""

if (cell == null) {

return cellValue

}

switch (cell.getCellType()) {

case HSSFCell.CELL_TYPE_NUMERIC:

cellValue = formater.format(cell.getNumericCellValue())

break

case HSSFCell.CELL_TYPE_STRING:

cellValue = cell.getStringCellValue()

break

case HSSFCell.CELL_TYPE_BLANK:

cellValue = cell.getStringCellValue()

break

case HSSFCell.CELL_TYPE_BOOLEAN:

cellValue = Boolean.valueOf(cell.getBooleanCellValue()).toString()

break

case HSSFCell.CELL_TYPE_ERROR:

cellValue = String.valueOf(cell.getErrorCellValue())

break

default:

cellValue = ""

}

return cellValue.trim()

}

// 读取pdf文件

public String readPDF(String file) throws IOException {

String result = null

FileInputStream is = null

PDDocument document = null

try {

is = new FileInputStream(file)

PDFParser parser = new PDFParser(is)

parser.parse()

document = parser.getPDDocument()

PDFTextStripper stripper = new PDFTextStripper()

result = stripper.getText(document)

} finally {

if (is != null) {

is.close()

}

if (document != null) {

document.close()

}

}

return result

}

// 读取doc文件

public String readWORD(String file) throws Exception {

String returnStr = ""

try {

WordExtractor wordExtractor = new WordExtractor(new FileInputStream(new File(file)))

returnStr = wordExtractor.getText()

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

return returnStr

}

// 读取docx文件

public String readWORD2007(String file) throws Exception {

return new XWPFWordExtractor(POIXMLDocument.openPackage(file)).getText()

}

// 读取txt文件

public String readTXT(String file) throws IOException {

String encoding = ReadFileUtils.get_charset(new File(file))

if (encoding.equalsIgnoreCase("GBK")) {

return FileUtils.readFileToString(new File(file), "gbk")

} else {

return FileUtils.readFileToString(new File(file), "utf8")

}

}

private static String get_charset(File file) throws IOException {

String charset = "GBK"

byte[] first3Bytes = new byte[3]

BufferedInputStream bis = null

try {

boolean checked = false

bis = new BufferedInputStream(new FileInputStream(file))

bis.mark(0)

int read = bis.read(first3Bytes, 0, 3)

if (read == -1)

return charset

if (first3Bytes[0] == (byte) 0xFF &&first3Bytes[1] == (byte) 0xFE) {

charset = "UTF-16LE"

checked = true

} else if (first3Bytes[0] == (byte) 0xFE

&&first3Bytes[1] == (byte) 0xFF) {

charset = "UTF-16BE"

checked = true

} else if (first3Bytes[0] == (byte) 0xEF

&&first3Bytes[1] == (byte) 0xBB

&&first3Bytes[2] == (byte) 0xBF) {

charset = "UTF-8"

checked = true

}

bis.reset()

if (!checked) {

// int len = 0

int loc = 0

while ((read = bis.read()) != -1) {

loc++

if (read >= 0xF0)

break

if (0x80 <= read &&read <= 0xBF) // 单独出现BF以下的,也算是GBK

break

if (0xC0 <= read &&read <= 0xDF) {

read = bis.read()

if (0x80 <= read &&read <= 0xBF) // 双字节 (0xC0 - 0xDF)

// (0x80

// - 0xBF),也可能在GB编码内

continue

else

break

} else if (0xE0 <= read &&read <= 0xEF) {// 也有可能出错,但是几率较小

read = bis.read()

if (0x80 <= read &&read <= 0xBF) {

read = bis.read()

if (0x80 <= read &&read <= 0xBF) {

charset = "UTF-8"

break

} else

break

} else

break

}

}

// System.out.println( loc + " " + Integer.toHexString( read )

// )

}

} catch (Exception e) {

e.printStackTrace()

} finally {

if (bis != null) {

bis.close()

}

}

return charset

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11748128.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存