輸入
注意:本例中的方法并不實際符合您的開發場景,請不要直接copy
1、從檔案輸入,并将結果按行讀入放到一個字元串中
import java.io.*;
import java.nio.charset.StandardCharsets;
public class MyIo{
public static String inputStreamDemo(String fileName) throws IOException {
File file = new File(fileName);
if (file.exists()){
InputStream inputStream = new FileInputStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,StandardCharsets.UTF_8));
String line = "";
String ans = "";
while ((line = bufferedReader.readLine())!= null){
ans = ans + line + "\r\n";
}
bufferedReader.close();
inputStream.close();
}
return null;
}
}
java中的輸入流利用了裝飾者模式,通過重重初始化,最終将對一個檔案的讀取裝飾成一個 BufferedReader 對象,然後利用其getLine方法按行讀取内容。值得一提的是,在windows環境中,回車其實是由 \r\n 兩個字元構成,而在linux系列作業系統中,回車是由 \n 字元構成,是以我們有時候會發現,從Linux伺服器導出的檔案,在windows環境打開并沒有換行效果。
2、從鍵盤輸入
public static String scannerDemo(){
Scanner scanner = new Scanner(System.in);
String ans = "";
while (scanner.hasNext()){
String tmp = scanner.nextLine();
ans = ans + tmp + "\n";
}
return ans;
}
從鍵盤輸入指的是,當程式運作起來之後,将滑鼠光标放到運作程式的地方,在鍵盤出入,程式可以擷取到。
3、從docx(文檔)中輸入,結果放到一個字元串中
import com.chaojilaji.util.service.WordService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public static String docxDemo(String folderName) throws IOException {
File file = new File(folderName);
File[] files = file.listFiles();
if (Objects.nonNull(files) && files.length > 0) {
for (File file1 : files) {
if (file1.isDirectory()) continue;
// TODO: 2019/6/14 讀取docx
String newName = folderName+"\\"+file1.getName();
InputStream inputStream = new FileInputStream(newName);
XWPFDocument xwpfDocument = new XWPFDocument(inputStream);
List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
String value = "";
for (XWPFParagraph xwpfParagraph : paragraphs){
value = value + "\r\n" + xwpfParagraph.getText();
}
return value;
}
}
return null;
}
4、從xlsx(表格)中輸入
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public static void xlsxDemo(String fileName) throws IOException{
File file = new File(fileName);
String ans = "";
if (file.exists()){
InputStream inputStream = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(inputStream));
int sheetNumber = workbook.getNumberOfSheets();
for(int i=0;i<sheetNumber;i++){
HSSFSheet sheet = workbook.getSheetAt(i);
int rowsNumber = sheet.getPhysicalNumberOfRows();
for (int j=0;j<rowsNumber;j++){
if (j==0){
continue;
}
HSSFRow row = sheet.getRow(j);
int cellNumber = row.getPhysicalNumberOfCells();
for (int k=0;k<cellNumber;k++){
if (k<3){
HSSFCell cell = row.getCell(k);
if (Objects.nonNull(cell)){
ans = ans + "\n" +cell.getStringCellValue();
}
}
}
ans = ans +"\n\n"+ "---------------------------------------内容分隔符--------------------------------------"+"\n\n";
}
}
}
return ans;
}