導航:首頁 > 文件目錄 > java讀取文件內容並顯示在頁面上

java讀取文件內容並顯示在頁面上

發布時間:2024-04-24 17:04:37

java設計並實現一個應用程序,能夠讀取一個文本文件中的內容並顯示,同時能夠計算出文本中的行數。

importjava.io.File;
importjava.util.Scanner;

publicclassTest{
publicstaticvoidmain(String[]args){
System.out.println("行數:"+getLineCountOfFile("c:\1.txt"));
}

(StringfilePath){
intlineCount=0;
Scannerscanner=null;
try{
scanner=newScanner(newFile(filePath));

while(scanner.hasNextLine()){
System.out.println("文件內容:"+scanner.nextLine());
++lineCount;
}
}catch(Exceptione){
}finally{
if(scanner!=null){
scanner.close();
}
}
returnlineCount;
}
}

現在c盤下新建一個文本文件 名字是1.txt , 裡面輸入一些內容 ,然後執行上面的代碼, 可以讀取內容,統計行數。也可以讀出空白行

㈡ java,swing,awt,圖形用戶界面:怎麼讀取一個本地文本文件並將該文件內容在圖形界面的文本區顯示

按照你的要求編寫的Java圖形界面讀取文本文件的程序如下(注意注釋中的提醒)

importjava.awt.BorderLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.BufferedReader;
importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.IOException;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.jscrollPane;
importjavax.swing.JTextArea;
{
Stringfilename="D:\tmp\temp.txt";//這里寫你准備好的文本文件的全路徑名
JTextAreajta=newJTextArea(5,3);
JScrollPanejsp=newJScrollPane(jta);
JButtonjb=newJButton("讀取文件");
JPaneljp=newJPanel();
B(){
setTitle("讀取文本文件");
jb.addActionListener(this);
jp.add(jb);
add(jsp,BorderLayout.CENTER);
add(jp,BorderLayout.SOUTH);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
publicstaticvoidmain(String[]args){
newB();
}
@Override
publicvoidactionPerformed(ActionEvente){
if(e.getSource()==jb){
readFile(filename);
}
}
publicvoidreadFile(Stringfilename2){
FileReaderfr=null;
BufferedReaderbr=null;
try{
fr=newFileReader(filename2);
br=newBufferedReader(fr);
Stringstr;
while((str=br.readLine())!=null){
jta.append(str+" ");
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
br.close();
fr.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

運行結果

文本文件 temp.txt的內容

天下一家
擁抱明天
永遠的朋友

㈢ java 如何讀取指定文件夾內的所有文件夾及文件,然後在頁面上以樹的形式顯示出來。

我給你一個讀取指定文件夾下面的所有文件夾,和文件的代碼。
至於頁面上用樹來顯示,html的話,這個有點麻煩。
swing的話,你就只需要用DefaultTreeModel.add(new TreeNode("XXX"));

public class GetAllFiles{
private String filePath = "C:/windows"; // 讀取C:/windos文件
private File f = null;

public GetAllFiles(){
f = new File(filePath);
}

public List<File> getAllFile(){
File[] fileInF = f.listFiles(); // 得到f文件夾下面的所有文件。
List<File> list = new List<File>();
for(File file : fileInF){
list.add(file);
}
return list;
}

public static void main(String[] args){
new GetAllFiles().getAllFile();
}
}

㈣ java讀取文件信息並顯示在界面上

final JTextArea edit = new JTextArea(30, 60);

s= br.readLine();//讀取下一行
textarea對象的read方法讀入:
FileReader reader = new FileReader( "xxx.txt" ); 這里要指定文件啊
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
接下來就要保存到全局變數。

㈤ JAVA怎麼做點擊按鈕促發事件彈出瀏覽窗口選擇excel文件讀取,並顯示到另外一個界面上,請給出主要代碼

package com.excel;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.swing.JTextArea;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
* 解析Excel的類
*/
public class ExcelOperate {
private JTextArea area;
private String fileName;

/**
* 構造方法傳值
*
* @param area
* 顯示Excel內容的位置
* @param fileName
* Excel文件名
*/
public ExcelOperate(JTextArea area, String fileName) {
this.area = area;
this.fileName = fileName;
}

/**
* 解析Excel文件
*/
public void parseExcel() {
File file = new File(fileName);
String[][] result = null;
try {
result = getData(file, 1);
} catch (IOException e) {
e.printStackTrace();
}
int rowLength = result.length;
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < result[i].length; j++) {
area.append(result[i][j] + "\t\t");
}
area.append("\n");
}

}

/**
* 讀取Excel的內容,第一維數組存儲的是一行中格列的值,二維數組存儲的是多少個行
*
* @param file
* 讀取數據的源Excel
* @param ignoreRows
* 讀取數據忽略的行數,比喻行頭不需要讀入 忽略的行數為1
* @return 讀出的Excel中數據的內容
* @throws FileNotFoundException
* @throws IOException
*/
public static String[][] getData(File file, int ignoreRows)
throws FileNotFoundException, IOException {
List<String[]> result = new ArrayList<String[]>();
int rowSize = 0;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
file));
// 打開HSSFWorkbook
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
HSSFSheet st = wb.getSheetAt(sheetIndex);
// 第一行為標題,不取
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum() + 1;
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}
String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;
for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 導入時如果為公式生成的數據則無值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
default:
value = "";
}
}
if (columnIndex == 0 && value.trim().equals("")) {
break;
}
values[columnIndex] = rightTrim(value);
hasValue = true;
}

if (hasValue) {
result.add(values);
}
}
}
in.close();
String[][] returnArray = new String[result.size()][rowSize];
for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = (String[]) result.get(i);
}
return returnArray;
}

/**
* 去掉字元串右邊的空格
*
* @param str
* 要處理的字元串
* @return 處理後的字元串
*/
public static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);
}
}
------------------------------------------------------------------------------------------
package com.excel;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
* 主界面,按鈕響應事件,文本域輸出Excel內容
*/
public class OpenExcel extends JFrame implements ActionListener {
private JButton button;
private JScrollPane pane;
private JTextArea area;

public OpenExcel() {
super("解析Excel");

button = new JButton("點我選擇Excel文件");
button.addActionListener(this);

area = new JTextArea();
pane = new JScrollPane(area);

this.add(button, BorderLayout.NORTH);
this.add(pane);
this.setSize(300, 300);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}

// 按鈕事件
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();// 文件選擇對話框
chooser.setAcceptAllFileFilterUsed(false);// 取消所有文件過濾項
chooser.setFileFilter(new FileNameExtensionFilter("Excel文件", "xls"));// 設置只過濾擴展名為.xls的Excel文件

int i = chooser.showOpenDialog(this);// 打開窗口
if (i == JFileChooser.APPROVE_OPTION) {
this.setLocation(0, 0);
this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
new ExcelOperate(area, chooser.getSelectedFile().getAbsolutePath())
.parseExcel();
}
}

public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new OpenExcel();
}
}

閱讀全文

與java讀取文件內容並顯示在頁面上相關的資料

熱點內容
linuxcppunit安裝 瀏覽:963
自慰韓國電影 瀏覽:496
PE系統拷貝文件提示需要許可權 瀏覽:644
校園四大天王電影 瀏覽:299
手機emmc編程器哪個好 瀏覽:35
法國禁忌十大片 瀏覽:232
飛盧app怎麼注冊成為作者 瀏覽:400
路由器網路mtu 瀏覽:70
穿越電影世界在現實中搞科研的小說 瀏覽:661
香港粵語電影 瀏覽:787
s/1BlWF6VD6VcvY3R0zOb5t5w 瀏覽:866
蘋果13手機數據線怎麼用 瀏覽:696
資料庫存儲形式 瀏覽:533
男主經常被逆推且有恐女症的小說 瀏覽:474
如何禁止廣聯達服務後台訪問網路 瀏覽:616
重生從造手機開始 瀏覽:831
台灣影視在線 瀏覽:763
孩子們的秘密演員是誰 瀏覽:150
js文件可以刪除文件 瀏覽:743
安卓手機如何打開qct文件 瀏覽:504

友情鏈接