Java读取txt文件中指定行内容
- 格式:doc
- 大小:55.50 KB
- 文档页数:4
Java读取TXT文本文件乱码解决方案今天在解析一个文本文件的时候出现了乱码,以前从未遇到,花了点时间解决了,在此总结一下:首先,先看一下解析的代码:private String[] getProjectData(File file){String[] data = null;try {BufferedReader br = new BufferedReader(new FileReader(file));String str = br.readLine();data = str.split(”\t”);br。
close();}catch(FileNotFoundException e) {e.printStackTrace();}catch(IOException e) {e。
printStackTrace();}return data;}这个方法很简单,就是获取txt文件中的一行数据,然后转换为数组,我这个文本中只有一行。
就这种情况下获取到的str是乱码,我想出现乱码肯定是字符集编码的问题,然后自己新建了一个文本文档测试没有问题(开始用的文本时别的程序导出的),所以我估计是开始那个txt文件编码的问题,查看发现是Unicode编码(如何查看txt的编码呢,教你一个笨笨的办法:打开文件——另存为,然后看到最下面的编码,默认选择的就是当前文档的编码格式),问题就出现在这里.问题找到了就好解决了,修改代码为:private String[] getProjectData(File file){String[] data = null;try {BufferedReader br = new BufferedReader(newInputStreamReader(new FileInputStream(file),”UTF—16"));String str = br。
readLine();data = str。
Java读取TXT文件的多种方式按行读取TXT文件package zc;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class readLine {public static void main(String[] args) {// TODO Auto-generated method stubFile file = new File("C:/zc.txt");BufferedReader reader = null;String tempString = null;int line =1;try {System.out.println("以行为单位读取文件内容,一次读一整行:");reader = new BufferedReader(new FileReader(file));while ((tempString = reader.readLine()) != null) {System.out.println("Line"+ line + ":" +tempString);line ++ ;}reader.close();} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}finally{if(reader != null){try {reader.close();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}}}}}按字节读取TXT文件package zc;import java.io.File;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException;import java.io.InputStream;public class readerFileByChars {public static void main(String[] args) {// TODO Auto-generated method stubFile file = new File("c:/zc.txt");InputStream in = null;byte[] tempByte = new byte[1024];int byteread = 0;try {System.out.println("以字节为单位读取文件内容,一次读多个字节:");in = new FileInputStream(file);while ((byteread = in.read(tempByte)) != -1 ) {System.out.write(tempByte, 0, byteread);}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if (in != null) {try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} }}。
Java如何读取文本文件Java具有简单性、面向对象、分布式、健壮性、安全性、平台的独立与可移植性、多线程、动态性等特点。
Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。
以下是店铺为大家搜索整理的如何读取文本文件,希望能给大家带来帮助!更多精彩内容请及时关注我们应届毕业生网!下面的代码是读取文本文件的例子,程序会读取text.txt文件,并将它的内容显示出来。
1 import java.io.BufferedReader;2 import java.io.File;3 import java.io.FileReader;4 import java.io.FileNotFoundException;5 import java.io.IOException;67 public class ReadTextFileExample8 {9 public static void main(String[] args)10 {11 File file = new File("test.txt");12 StringBuffer contents = new StringBuffer();13 BufferedReader reader = null;1415 try16 {17 reader = new BufferedReader(new FileReader(file));18 String text = null;1920 // repeat until all lines is read21 while ((text = reader.readLine()) != null)22 {23 contents.append(text)24 .append(System.getProperty(25 "line.separator"));26 }。
java学习笔记——jsp简单⽅法读取txt⽂本数据该⽅法不需要数据库和excel插件,程序简单,实现速度快。
⽬标:如下⾯的txt⽂档有200多个,每个txt⽂档都有20条不规则记录,需要将每个⽂档中的每条数据保存到excel中。
这些txt是从⽹站中保存下来的,由于⼀些⽹站要验证session和ip,所以不是很好实现⽹上抓取,就对下载下来的⽂本⽂件进⾏处理,以后再研究⽹上抓取的过程。
⽂本⽚段例⼦:HIGHLY CITED PAPERS FOR (PEOPLES R CHINA)Sorted by: Citations Publication Year Journal Title881 - 900 (of 6910) [ 41 | 42 | 43 | 44 | 45 | 46 | 47 |48 | 49 | 50 ]Page 45 of 346881 Citations: 3Title:GEVREY HYPOELLIPTICITY FOR A CLASS OF KINETIC EQUATIONSAuthors:CHEN H; LI WX; XU CJSource:COMMUN PART DIFF EQUAT 36 (4): 693-728 2011Addresses:Wuhan Univ, Sch Math & Stat, Wuhan 430072, Peoples RChina.Univ Rouen, CNRS, UMR 6085, St Etienne, France.Field:MATHEMATICS882 Citations: 3Title:HIGHER AUSLANDER ALGEBRAS ADMITTING TRIVIAL MAXIMAL ORTHOGONALSUBCATEGORIESAuthors:HUANG ZY; ZHANG XJSource:J ALGEBRA 330 (1): 375-387 MAR 15 2011Addresses:Nanjing Univ, Dept Math, Nanjing 210093, Jiangsu Prov,Peoples R China.Nanjing Univ Informat Sci & Technol, Coll Math & Phys, Nanjing210044, Jiangsu Prov, Peoples R China.Field:MATHEMATICS883 Citations: 3Title:PREDATOR-PREY SYSTEM WITH STRONG ALLEE EFFECT IN PREY例⼦中红⾊字体为需要抽取的字段,遇到的问题有:每⼀页都有多条记录,如何区分各个记录;每个字段的⾏数都不⼀样,如何确定其⾏数。
java读取txt⽂件并输出结果这篇⽂章主要介绍了java读取txt⽂件并输出结果,⽂中通过⽰例代码介绍的⾮常详细,对⼤家的学习或者⼯作具有⼀定的参考学习价值,需要的朋友可以参考下描述:1.java读取指定txt⽂件并解析⽂件格式:代码:package com.thinkgem.wlw.modules.midea;import java.io.*;import java.util.ArrayList;import java.util.List;/*** @Author: zhouhe* @Date: 2019/6/19 8:48*/public class Test {public static void main(String[] args) {// ⽂件夹路径String path = "D:\\input.txt";try {List<String> scanListPath = readFile02(path);// System.out.println(scanListPath);for (int i = 0; i < scanListPath.size(); i++) {String mytext = scanListPath.get(i);//替换所有制表符mytext = mytext.replaceAll("\t",",");System.out.println(mytext);//每⼀⾏都转化为新的数组,根据下标去判断参数值对应的参数是什么String [] strArr= mytext.split(","); //注意分隔符是需要转译for (int m = 0; m < strArr.length; m++) {// System.out.println(strArr[m]);switch(m){case 0:System.out.println("时间:"+strArr[m]);break;case 1:System.out.println("甲烷:"+strArr[m]);break;case 2:System.out.println("总烃:"+strArr[m]);break;case 3:System.out.println("⾮甲烷总烃:"+strArr[m]);break;case 4:System.out.println("氨⽓:"+strArr[m]);break;case 5:System.out.println("硫化氢:"+strArr[m]);break;case 6:System.out.println("氧⽓:"+strArr[m]);break;default:break;}}}} catch (IOException e) {System.out.println("有异常,⽆法读取");}}/*** 读取⼀个⽂本⼀⾏⼀⾏读取** @param path* @return* @throws IOException*/public static List<String> readFile02(String path) throws IOException {// 使⽤⼀个字符串集合来存储⽂本中的路径,也可⽤String []数组List<String> list = new ArrayList<String>();FileInputStream fis = new FileInputStream(path);// 防⽌路径乱码如果utf-8 乱码改GBK eclipse⾥创建的txt ⽤UTF-8,在电脑上⾃⼰创建的txt ⽤GBKInputStreamReader isr = new InputStreamReader(fis, "UTF-8");BufferedReader br = new BufferedReader(isr);String line = "";while ((line = br.readLine()) != null) {// 如果 t x t⽂件⾥的路径不包含---字符串这⾥是对⾥⾯的内容进⾏⼀个筛选if (stIndexOf("---") < 0) {list.add(line);}}br.close();isr.close();fis.close();return list;}}结果:2.java读取指定⽂件夹下的所有txt⽂件并输出内容(我这⾥⼀个⽂件夹下⾯有 2 个txt⽂件):代码:package com.thinkgem.wlw.modules.midea;import java.io.*;/*** @Author zhouhe* @Date 2019/10/10 13:10*/public class Test2 {/**新建⼀个类把下⾯代码放进去,注意要设置basePath(你要读取的⽂件夹),读取和写⼊的⽅法也都写好了.你可以根据⾃⼰的需求掉⽤就⾏了**/ static String basePath="D:\\测试";/** * 查找⽂件夹下所有符合csv的⽂件 * * @param dir 要查找的⽂件夹对象 * */public static void findFile(File dir) throws IOException {File[] dirFiles = dir.listFiles();for(File temp : dirFiles){if(!temp.isFile()){findFile(temp);}//查找指定的⽂件if(temp.isFile() && temp.getAbsolutePath().endsWith(".txt") ){//获取⽂件路径,包含⽂件名String filePath = temp.getAbsolutePath();//获取⽂件名String fileName = temp.getName();System.out.println(temp.isFile() + " " + temp.getAbsolutePath());readFileContent(temp);}}}/** * @param file 要读取的⽂件对象 * @return 返回⽂件的内容 * */public static String readFileContent(File file) throws IOException{FileReader fr = new FileReader(file);BufferedReader br = new BufferedReader(fr);StringBuffer sb = new StringBuffer();while(br.ready()){// sb.append(br.readLine());System.out.println(br.readLine());}System.out.println(sb.toString());return sb.toString();}/** * @param file 要写⼊的⽂件对象 * @param content 要写⼊的⽂件内容 * */public static void writeFileContent(File file,String content) throws IOException{FileWriter fw = new FileWriter(file);fw.write(content);fw.flush();fw.close();}public static void main(String[] args) {try {findFile(new File(basePath));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}结果:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
java读取txt⽂件⼀、读取txt⽂件。
1、步骤 :①、创建⽂件句柄File file = new File(filePath);②、将⽂件内容读取到内存中new FileInputStream(file)③、封装数据 InputStreamReaderInputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding)④、读取数据BufferedReader bufferedReader = new BufferedReader(read); 每⾏数据bufferedReader.readLine()2、场景: txt⽂件内容:123456...读取每⾏内容, 并将每⾏内容⽤ , 拼接成 123,456public class ReadTxt {public static void main(String[] args) {String filePath = "/Users/xupengwei/Downloads/test.txt";readTxtFile(filePath );}public static void readTxtFile(String filePath) {try {String encoding = "GBK";File file = new File(filePath);if (file.isFile() && file.exists()) { // 判断⽂件是否存在InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read);String lineTxt = null;StringBuffer sb = new StringBuffer();while ((lineTxt = bufferedReader.readLine()) != null) {sb.append(lineTxt);sb.append(",");}System.out.println(sb.toString());read.close();} else {System.out.println("找不到指定的⽂件");}} catch (Exception e) {System.out.println("读取⽂件内容出错");e.printStackTrace();}}}⼆、拓展...场景 : 正则匹配。
Java读取⽂件内容的六种⽅法1.Scanner第⼀种⽅式是Scanner,从JDK1.5开始提供的API,特点是可以按⾏读取、按分割符去读取⽂件数据,既可以读取String类型,也可以读取Int类型、Long类型等基础数据类型的数据。
@Testvoid testReadFile1() throws IOException {//⽂件内容:Hello World|Hello ZimugString fileName = "D:\\data\\test\\newFile4.txt";try (Scanner sc = new Scanner(new FileReader(fileName))) {while (sc.hasNextLine()) { //按⾏读取字符串String line = sc.nextLine();System.out.println(line);}}try (Scanner sc = new Scanner(new FileReader(fileName))) {eDelimiter("\\|"); //分隔符while (sc.hasNext()) { //按分隔符读取字符串String str = sc.next();System.out.println(str);}}//sc.hasNextInt() 、hasNextFloat() 、基础数据类型等等等等。
//⽂件内容:1|2fileName = "D:\\data\\test\\newFile5.txt";try (Scanner sc = new Scanner(new FileReader(fileName))) {eDelimiter("\\|"); //分隔符while (sc.hasNextInt()) { //按分隔符读取Intint intValue = sc.nextInt();System.out.println(intValue);}}}上⾯的⽅法输出结果如下:Hello World|Hello ZimugHello WorldHello Zimug122.Files.lines (Java 8)如果你是需要按⾏去处理数据⽂件的内容,这种⽅式是我推荐⼤家去使⽤的⼀种⽅式,代码简洁,使⽤java 8的Stream流将⽂件读取与⽂件处理有机融合。
一、介绍在编程领域,经常会有需要获取指定类型的文件的需求,特别是在Java开发中。
Java作为一种面向对象的程序设计语言,提供了丰富的API和库,使得获取指定类型文件的操作变得相对简单。
本文将介绍Java中获取指定类型文件的方法,以及在实际项目开发中的应用。
二、使用File类的listFiles()方法Java中的File类提供了用于文件操作的大量方法,其中listFiles()方法可以获取指定目录下的所有文件和子目录。
我们可以结合文件过滤器来获取指定类型的文件。
1. 使用FilenameFilter过滤器我们可以实现一个FilenameFilter接口的实例,然后将其传递给listFiles()方法,以获得指定类型的文件列表。
以下为一个示例代码:```javaFile folder = new File("D:/documents");File[] files = folder.listFiles(new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {return name.endsWith(".txt");}});```上述代码中,我们通过传递一个实现FilenameFilter接口的匿名类来过滤出所有以“.txt”结尾的文件。
2. 使用FileFilter过滤器除了FilenameFilter外,我们还可以使用FileFilter接口来实现文件过滤。
FileFilter接口只包含一个accept()方法,用于过滤文件。
以下为一个示例代码:```javaFile folder = new File("D:/documents");File[] files = folder.listFiles(new FileFilter() {@Overridepublic boolean accept(File pathname) {return pathname.getName().endsWith(".txt");}});上述代码中,我们通过传递一个实现FileFilter接口的匿名类来过滤出所有以“.txt”结尾的文件。
Java 读取Word文本/段落格式属性本文介绍通过Java后端程序代码来读取Word文本和段落格式的方法。
本次测试环境如下:●Word版本:2013●编译环境:IntelliJ IDEA2018●Work库:free spire.doc.jar 3.9.0●JDK版本:1.8.0通过textrange.getCharacterFormat()方法读取文本字符串格式,通过paragraph.getFormat()读取段落格式,读取具体文字及段落属性时,可支持读取字体、字号、文字颜色、文字背景、文字是否加粗或倾斜、文字下划线、大小写、边框、上标下标、行距、段落缩进、对齐方式、段落边框、背景等等,下表中罗列了所有可支持读取的样式属性,供参考:读取文本格式getCharacterFormat():读取段落格式:getFormat()用于测试的Word文档:Java示例代码import com.spire.doc.*;import com.spire.doc.documents.Paragraph;import com.spire.doc.documents.TextSelection;import com.spire.doc.fields.TextRange;import java.awt.*;public class GetTextFormat {public static void main(String[] args) {//加载Word源文档Document doc = new Document();doc.loadFromFile("test.docx");//获取段落数量int count = doc.getSections().get(0).getParagraphs().getCount();System.out.println("总共含有段落数:" + count);//查找指定文本TextSelection textSelections = doc.findString("东野圭吾", false, true);//获取字体名称String fontname =textSelections.getAsOneRange().getCharacterFormat().getFontName();//获取字体大小float fontsize =textSelections.getAsOneRange().getCharacterFormat().getFontSize();System.out.println("字体名称:" + fontname +"\n"+"字体大小:"+fontsize);//获取第二段Paragraph paragraph2 = doc.getSections().get(0).getParagraphs().get(1);//获取段落行距float linespage = paragraph2.getFormat().getLineSpacing();System.out.println("段落行距:" + linespage);//遍历段落中的子对象for (int z = 0; z < paragraph2.getChildObjects().getCount(); z++){Object obj2 = paragraph2.getChildObjects().get(z);//判定是否为文本if (obj2 instanceof TextRange){TextRange textRange2 = (TextRange) obj2;//获取文本颜色Color textcolor = textRange2.getCharacterFormat().getTextColor();if (!(textcolor.getRGB() == 0)){System.out.println("文本颜色:" + textRange2.getText() + textcolor.toString());}//获取字体加粗效果boolean isbold = textRange2.getCharacterFormat().getBold();if (isbold == true){System.out.println("加粗文本:" + textRange2.getText());}//获取字体倾斜效果boolean isitalic = textRange2.getCharacterFormat().getItalic();if (isitalic == true){System.out.println("倾斜文本:" + textRange2.getText());}//获取文本背景String text = textRange2.getText();Color highlightcolor =textRange2.getCharacterFormat().getHighlightColor();//获取文本的高亮颜色(即突出显示颜色)if (!(highlightcolor.getRGB() == 0 )){System.out.println("文本高亮:" + text +highlightcolor.toString());//输出高亮的文本和颜色}Color textbackgroundcolor =textRange2.getCharacterFormat().getTextBackgroundColor();//获取文字背景(底纹)if (!(textbackgroundcolor.getRGB()==0)){System.out.println("文本背景:" + text + textbackgroundcolor.toString());//输出有背景的文本和颜色}}}}}运行程序,输入获取结果:。
获取文本内容与读取文本指定行数内容浅析(java)
在此项目中直接套用以前工程中获取文本内容的方法发现一直提示“数组下标越界”,通过分析和查找得出以下心得:
获取文本内容:
private static final String CHART_PATH ="D://data3";
public static void main(String[] args) throws
RowsExceededException,WriteException, BiffException{
try {
readFileByLines(CHART_PATH+".txt");
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void readFileByLines(String fileName) throws
IOException,RowsExceededException,WriteException{
//打开文件
WritableWorkbook book = Workbook.createWorkbook(
new File(CHART_PATH+".xls"));
WritableSheet sheet = book.createSheet("看我", 0);
//读取txt文件内容
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"GBK");
BufferedReader reader = null;
try {
reader = new BufferedReader(isr);
String temString = null;
//一次读入一行,以null结束
int i = 0;
while((temString = reader.readLine())!= null){
System.out.println("+++++++"+temString);
String[] str = temString.split(",");
for(int j= 0;j<str.length;j++){
Label label = new Label(j,i,str[j]);
sheet.addCell(label);
// System.out.println(str[j]);
System.out.println("----------"+str[j]);
}
i++;
}
//写入
book.write();
try {
book.close();
} catch (WriteException e) {
// TODO: handle exception
e.printStackTrace();
}
reader.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(reader!=null){
reader.close();
}
}
}
从以上代码可以看出是每行读取数据然后存入新的数组中,按道理说可以通过类似int a =0;
a =Integer.parseInt(str[0]);
来获取新数组中的第一个元素,但是此时工程会一直报
ng.ArrayIndexOutOfBoundsException: 0,
说明此时不能直接这么从新数组中获取数据
获取某一行文本信息:
为了获取想要的目标数据可以这么做:
package testTxt;
import java.io.*;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// 指定读取的行号
int lineNumber =5;
// 读取文件
File sourceFile = new File("D://data3.txt");
try {
// 读取指定的行
readAppointedLineNumber(sourceFile, lineNumber);
// readAppointedLineNumber(sourceFile, lineNumber);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 读取文件指定行。
static void readAppointedLineNumber(File sourceFile, int lineNumber) throws IOException {
FileReader in = new FileReader(sourceFile);
LineNumberReader reader = new LineNumberReader(in);
String s = "";
if (lineNumber <= 0 || lineNumber > getTotalLines(sourceFile)) { System.exit(0);
}
int lines = 0;
while (s != null) {
lines++;
s = reader.readLine();
if((lines - lineNumber) == 0) {
System.out.println(s+"wo zai zhe");
int a =0;
a =Integer.parseInt(s);
System.out.println(a+"MMMMMMMMMMMMMMMMMMMMM");
System.exit(0);
}
}
reader.close();
in.close();
}
// 文件内容的总行数。
static int getTotalLines(File file) throws IOException {
FileReader in = new FileReader(file);
LineNumberReader reader = new LineNumberReader(in);
String s = reader.readLine();
int lines = 0;
while (s != null) {
lines++;
s = reader.readLine();
if(lines>=2){
if(s!=null){
// System.out.println(s+"LLLLLLLLLL");
}
}
}
reader.close();
in.close();
return lines;
}
}
从上述代码中可以很清楚的看出想要获取某一行的数据,只需要传入此行的lineNumber就行。