⑴ java如何實現讀一個文件(非文本文件)後輸出其中自己指定的一部分
importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.LineNumberReader;
importjava.util.Scanner;
/**
*讀取文件指定行數內容
*@authoryoung
*
*/
publicclassReadSelectedLine{
staticvoidreadLineVarFile(StringfileName,intlineNumber)
throwsIOException{
BufferedReaderreader=newBufferedReader(newInputStreamReader(
newFileInputStream(fileName)));
Stringline=reader.readLine().toString();
if(lineNumber<0||lineNumber>getTotalLines(fileName)){
System.out.println("不在文件的行數范圍之內。");
}
intnum=0;
while(line!=null){
if(lineNumber==++num){
System.out.println("line"+lineNumber+":"+line);
}
line=reader.readLine();
}
reader.close();
}
//文件內容的總行數。
staticintgetTotalLines(StringfileName)throwsIOException{
BufferedReaderin=newBufferedReader(newInputStreamReader(
newFileInputStream(fileName)));
LineNumberReaderreader=newLineNumberReader(in);
Strings=reader.readLine();
intlines=0;
while(s!=null){
lines++;
s=reader.readLine();
}
reader.close();
in.close();
returnlines;
}
publicstaticvoidmain(String[]args)throwsIOException{
//讀取文件
StringfileName="c:\1.java";
//獲取文件的內容的總行數
inttotalNo=getTotalLines(fileName);
System.out.println("Thereare"+totalNo+"linesinthetext!");
//指定讀取的行號,此處也可以改成自由輸入
System.out.println("輸出文件第幾行內容?");
intlineNumber=newScanner(System.in).nextInt();
//讀取指定行的內容
readLineVarFile(fileName,lineNumber);
}
}
在C盤新建1.java文件,輸入任意內容,
⑵ java中如何實現文件的批量讀取並提取部分內容寫入一個新文件。 單一文件讀取寫入參照補充
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Testa
{
public static void main(String[] args)
{
//傳入參數為文件目錄
test("d:/a.txt");
}
public static void test(String filePath){
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
String []columnName = {"Id", "Name", "Languages", "Math", "English"}; //列名
int []courseIndexs = {2, 3, 4}; //課程對應的列
int i,j,index;
String line;
List> students = new ArrayList>();
//記錄Id和總值,用於排序
List> sortList = new ArrayList>();
try {
br.readLine(); //去掉第一行
while((line = br.readLine()) != null){
index = 0;
String []se = line.split(" ");
Map student = new HashMap();
for(i = 0; i < se.length; i++){
if("".equals(se[i])){
continue;
}
if(index >= columnName.length){
continue;
}
student.put(columnName[index], se[i]);
index++;
}
//計算平均值,總值
double total = 0;
for(j = 0; j < courseIndexs.length; j++){
total += Double.parseDouble((String) student.get(columnName[courseIndexs[j]]));
}
double average = total / courseIndexs.length;
//只取一位小數
average = Math.round(average * 10)/10;
student.put("Total", total);
student.put("Average", average);
Map sort = new HashMap();
sort.put("Id", student.get("Id"));
sort.put("Total", student.get("Total"));
sortList.add(sort);
students.add(student);
}
br.close();
//排序
for(i = 0; i < sortList.size(); i++){
for(j = i + 1; j < sortList.size(); j++){
if((Double)sortList.get(i).get("Total") < (Double)sortList.get(j).get("Total")){
Map temp = sortList.get(i);
sortList.set(i, sortList.get(j));
sortList.set(j, temp);
}
}
}
Map sortedId = new HashMap();
for(i = 0; i < sortList.size(); i++){
sortedId.put(sortList.get(i).get("Id"), i+1);
}
//設定序號
for(j = 0; j < students.size(); j++){
students.get(j).put("Order", sortedId.get(students.get(j).get("Id")));
}
//輸出(寫到原文件)
//PrintWriter pw = new PrintWriter(new File(filePath));
//輸出(寫到其他文件)
PrintWriter pw = new PrintWriter(new File("D:/b.txt"));
pw.println("Id\tName\tLan\tMath\tEnglish\tAverage\tTotal\tSort");
int cIndex;
for(i = 0; i < students.size(); i++){
Map st = students.get(i);
cIndex = 0;
pw.println(st.get(columnName[cIndex++]) + "\t" + st.get(columnName[cIndex++])
+ "\t" + st.get(columnName[cIndex++])+ "\t" + st.get(columnName[cIndex++])
+ "\t" + st.get(columnName[cIndex++])
+ "\t" + st.get("Total")
+ "\t" + st.get("Average")
+ "\t" + st.get("Order"));
}
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
⑶ java讀取部分文件內容,怎樣獲取所讀取這部分的大小
windows下文件換行默認追加" "的字元串,最後一行沒有。
StringBuffersb=newStringBuffer();
inti=0;
Stringfinfo=null;
floatnewL0=0;
floatorgL=file.length();
while((finfo=fr.readLine())!=null)
{
i++;
if((sb.length()+finfo.length())<orgL)
{
sb.append(finfo+" ");
}
else
{
sb.append(finfo);
}
System.out.println("第"+i+"行:"+finfo+",讀取長度:"+newL0+",字元總長度:"+orgL+",當前讀取進度:"+(sb.length()/orgL)*100+"%");
}
⑷ java讀取txt並獲取某一部分字元串
public static String readFile(String filepath) {
StringBuffer string=new StringBuffer();
BufferedReader br=null;
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(filepath));
br=new BufferedReader(isr);
String line = null;
while((line=br.readLine())!= null){
string.append(line);
string.append("
");
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return string.toString();
}
public static String rightStr(String str, int count) {
String result = "";
if (!strIsNull(str)) {
if (str.length() > count) {
result = str.substring(str.length() - count);
} else {
result = str;
}
}
return result;
}
給兩個方法你參考下
⑸ java讀取文件內容,分多個部分,每部分40位元組,現每次只發送了前40個位元組的內容,請幫忙看看哪裡的問題,謝謝.
int len = content.length(); 這句不對的。content.length()返回的字元長度而不是位元組長度。
對於非單位元組編碼而言content.length()長度永遠小於content.getBytes().length,只有對單位元組字元而言這兩個長度才相等。
另外分數組處理實在不是好辦法,即需要書寫更長的代碼,運行效率也低於用流方式處理的。
一下是我寫的兩種方式的處理代碼 你能明顯的比較出來。流只用一個循環,而位元組數組至少要一個雙循環。
Strings="實現dhl反對思考浪費你的身份了你看打發士大夫士大夫似的";
//數組方式
byte[]bs=s.getBytes();
intlength=5,len=bs.length/length,len1;
byte[]tmp=newbyte[length];
for(inti=0;i<len;i++){
for(intj=0;j<length;j++)
tmp[j]=bs[i*length+j];
System.out.println(Arrays.toString(tmp));
}
tmp=newbyte[length];
if((len1=bs.length%length)>0){
for(inti=0;i<len1;i++)
tmp[i]=bs[len*length+i];
System.out.println(Arrays.toString(tmp));
}
//流方式
InputStreamis=newByteArrayInputStream(s.getBytes());
intlength2=5,len2;
byte[]bs2=newbyte[length2];
try{
while((len2=is.read(bs2))>0){
if(len2!=length2)
Arrays.fill(bs2,len2,5,(byte)0);
System.out.println(Arrays.toString(bs2));
}
}catch(IOExceptione){
e.printStackTrace();
}
⑹ java文件讀取指定內容
給你寫了一個小方法,應該滿足你的要求了:
//url是你要讀取的文件的路徑,是所要求的包含的字元串如這里是「COMMON.9006 - 000332」。
public static void readWantedText(String url, String wanted) {
try {
FileReader fr = new FileReader(url);
BufferedReader br = new BufferedReader(fr);
String temp = "";// 用於臨時保存每次讀取的內容
while (temp != null) {
temp = br.readLine();
if (temp != null && temp.contains(wanted)) {
System.out.println(temp);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
用的話直接調用這個方法就可以了:例如
readWantedText("D:\\test.txt", "COMMON.9006 - 000332");
//注意java路徑需要在每條\前面在加條\表示轉義。
⑺ Java如何實現讀取一個txt文件的所有內容,然後提取所需的部分並把它寫入到另一個txt文件中
代碼如下:
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.util.ArrayList;
importjava.util.List;
publicclassApp{
/**
*保存list到指定文件
*@paramlist
*@paramfilePath
*@throwsIOException
*@throwsFileNotFoundException
*/
staticvoidsave(List<String>list,StringfilePath)throwsFileNotFoundException,IOException{
try(FileOutputStreamoutputStream=newFileOutputStream(filePath);
=newOutputStreamWriter(outputStream);
BufferedWriterwriter=newBufferedWriter(streamWriter)
){
for(Stringline:list){
writer.write(line+System.lineSeparator());
}
}
}
publicstaticvoidmain(String[]args)throwsIOException{
List<String>list1=newArrayList<>();
List<String>list2=newArrayList<>();
List<String>list3=newArrayList<>();
Filefile=newFile("d:/temp/0.txt");
try(FileInputStreamstream=newFileInputStream(file);
InputStreamReaderstreamReader=newInputStreamReader(stream);
BufferedReaderreader=newBufferedReader(streamReader)){
Stringline="";
while((line=reader.readLine())!=null){
//去除開始的數字
line=line.replaceFirst("\d+","");
if(line.contains("Organ")){
//包含Organ放入list1
list1.add(line);
}elseif(line.contains("Location")){
//包含Location放入list2
list2.add(line);
}elseif(line.contains("Person")){
//包含Person放入list3
list3.add(line);
}
}
}
if(!list1.isEmpty()){
save(list1,"d:/temp/1.txt");
}
if(!list2.isEmpty()){
save(list2,"d:/temp/2.txt");
}
if(!list3.isEmpty()){
save(list3,"d:/temp/3.txt");
}
}
}
⑻ Java如何讀取TXT文件中的部分數字
文件流的讀取你就自己搞定吧,下面的步驟如下:
String str ="shoes 25.3 5 126.5\ncloths 50.0 10 500.0\nsugar 1.25 1 1.25\ncoffee 3.0 7 21.0ntelephone 20.0 2 40.0\ncup 4.0 25 100.0";
String[] splitArray = str.trim().split("\n");
String[] newSplitArray = splitArray[splitArray.length-1].trim().split(" ");
double returnD =0;
for ( int i = 0; i < newSplitArray.length; i++ ) {
if(newSplitArray[i].matches("[\\d.]+")){
returnD+=Double.parseDouble(newSplitArray[i]);
}
}
System.out.println(returnD);
⑼ JAVA讀取指定文件裡面的指定內容
給你寫了一個小方法,應該滿足你的要求了:
//url是你要讀取的文件的路徑,wanted是所要求的包含的字元串如這里是「COMMON.9006 - 000332」。
public static void readWantedText(String url, String wanted) {
try {
FileReader fr = new FileReader(url);
BufferedReader br = new BufferedReader(fr);
String temp = "";// 用於臨時保存每次讀取的內容
while (temp != null) {
temp = br.readLine();
if (temp != null && temp.contains(wanted)) {
System.out.println(temp);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
用的話直接調用這個方法就可以了:例如
readWantedText("D:\\test.txt", "COMMON.9006 - 000332");
//注意java路徑需要在每條\前面在加條\表示轉義。
⑽ 如何利用java讀取磁碟文件中所需部分資源
先全部讀取出來,再判斷!