當前位置:首頁 » 編程語言 » javatxt

javatxt

發布時間: 2022-01-08 23:22:07

java結果輸出至txt

幫你修改了一下 你看看可以嗎


package com.isoftstone.;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Article {
//保存文章的內容
String content;
//保存分割後的單詞集合
String[] rawWords;
//保存統計後的單詞集合
String[] words;
//保存單詞對應的詞頻
int[] wordFreqs;
//構造函數,輸入文章內容
//提高部分:從文件中讀取
public Article() {
content =
"kolya is one of the richest films i've seen in some time . zdenek sverak plays a confirmed old bachelor ( who's likely to remain so ) , who finds his life as a czech cellist increasingly impacted by the five-year old boy that he's taking care of . though it ends rather abruptly-- and i'm whining , 'cause i wanted to spend more time with these characters-- the acting , writing , and proction values are as high as , if not higher than , comparable american dramas . this father-and-son delight-- sverak also wrote the script , while his son , jan , directed-- won a golden globe for best foreign language film and , a couple days after i saw it , walked away an oscar . in czech and russian , with english subtitles . ";
}
//對文章根據分隔符進行分詞,將結果保存到rawWords數組中
public void splitWord() {
//分詞的時候,因為標點符號不參與,所以所有的符號全部替換為空格
final char SPACE = ' '
content = content.replace(''', SPACE).replace(',', SPACE).replace('.', SPACE);
content = content.replace('(', SPACE).replace(')', SPACE).replace('-', SPACE);
rawWords = content.split("\s+");//凡是空格隔開的都算單詞,上面替換了', 所以I've 被分成2個 //單詞
}
//統計詞,遍歷數組
public void countWordFreq() {
//將所有出現的字元串放入唯一的set中,不用map,是因為map尋找效率太低了
Set<String> set = new TreeSet<String>();
for (String word : rawWords) {
set.add(word);
}
Iterator ite = set.iterator();
List<String> wordsList = new ArrayList<String>();
List<Integer> freqList = new ArrayList<Integer>();
//多少個字元串未知,所以用list來保存先
while (ite.hasNext()) {
String word = (String) ite.next();
int count = 0;//統計相同字元串的個數
for (String str : rawWords) {
if (str.equals(word)) {
count++;
}
}
wordsList.add(word);
freqList.add(count++);
}
//存入數組當中
words = wordsList.toArray(new String[0]);
wordFreqs = new int[freqList.size()];
for (int i = 0; i < freqList.size(); i++) {
wordFreqs[i] = freqList.get(i);
}
}
//根據詞頻,將詞數組和詞頻數組進行降序排序
public void sort() {
class Word {
private String word;
private int freq;
public Word(String word, int freq) {
this.word = word;
this.freq = freq;
}
}
//注意:此處排序,1)首先按照詞頻降序排列, 2)如果詞頻相同,按照字母降序排列,
//如 'abc' > 'ab' >'aa'
class WordComparator implements Comparator {
public int compare(Object o1, Object o2) {
Word word1 = (Word) o1;
Word word2 = (Word) o2;
if (word1.freq < word2.freq) {
return 1;
} else if (word1.freq > word2.freq) {
return -1;
} else {
int len1 = word1.word.trim().length();
int len2 = word2.word.trim().length();
String min = len1 > len2 ? word2.word : word1.word;
String max = len1 > len2 ? word1.word : word2.word;
for (int i = 0; i < min.length(); i++) {
if (min.charAt(i) < max.charAt(i)) {
return 1;
}
}
return 1;
}
}
}
List wordList = new ArrayList<Word>();
for (int i = 0; i < words.length; i++) {
wordList.add(new Word(words[i], wordFreqs[i]));
}
Collections.sort(wordList, new WordComparator());
for (int i = 0; i < wordList.size(); i++) {
Word wor = (Word) wordList.get(i);
words[i] = wor.word;
wordFreqs[i] = wor.freq;
}
}
//將排序結果輸出
public void printResult() {
System.out.println("Total " + words.length + " different words in the content!");
for (int i = 0; i < words.length; i++) {
System.out.println(wordFreqs[i] + " " + words[i]);
}
}
// 輸出到文本
private void outputResult() {
File file = new File("C:\output.txt");
try {
if (file.exists()) file.delete();
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
StringBuffer out = new StringBuffer();
for(int i = 0; i < words.length; i++) {
out.append(wordFreqs[i] + " " + words[i] + " ");
}
bw.write(out.toString());
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//測試類的功能
public static void main(String[] args) {
Article a = new Article();
a.splitWord();
a.countWordFreq();
a.sort();
a.printResult();
a.outputResult();
}
}

⑵ java 寫txt文件

import java.io.*;
public class Test {

public static void main(String[] args){
String s = new String();
String s1 = new String();
try {
File f = new File("E:\\123.txt");
if(f.exists()){
System.out.print("文件存在");
}else{
System.out.print("文件不存在");
f.createNewFile();//不存在則創建
}
BufferedReader input = new BufferedReader(new FileReader(f));

while((s = input.readLine())!=null){
s1 += s+"\n";
}
System.out.println(s1);
input.close();
s1 += "添加的內容!";

BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}

⑶ 如何用JAVA生成TXT文件

生成TXT的方法有很多的。常用位位元組流和字元流
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;

public class TextFileGenerator {
public static void main(String[] args) throws Exception {
method1();
method2();
}

private static void method1() throws Exception {

String txtContent = "Hello World!";

File file = new File("test1.txt");
FileWriter fw = new FileWriter(file);
fw.write(txtContent);
fw.close();

}

private static void method2() throws Exception {

String txtContent = "Hello World!";

File file = new File("test2.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(txtContent.getBytes());
fos.close();

}

}

⑷ java合並兩個txt文件並生成新txt

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.PrintStream;
importjava.util.Arrays;
importjava.util.Collections;
importjava.util.LinkedList;
importjava.util.Scanner;

publicclassTest
{
publicstaticfinalStringLINE=System.getProperty("line.separator");

publicstaticint[]readfile(Scannerinput)
{
int[]a=newint[0];
while(input.hasNextLine())
{
Stringline=input.nextLine().trim();
int[]dest=newint[a.length+1];
System.array(a,0,dest,0,a.length);
dest[dest.length-1]=Integer.parseInt(line);
a=dest;
}
input.close();
returna;
}

publicstaticvoidwritefile(PrintStreamoutput,int[]a)
{
output.append(Arrays.toString(a).replaceAll("[\[\]\s]","").replaceAll(",",LINE));
output.flush();
output.close();
}

publicstaticint[]merge(int[]a,int[]b)
{
int[]dest=newint[a.length+b.length];
System.array(a,0,dest,0,a.length);
System.array(b,0,dest,a.length,b.length);
returndest;
}
}

classTest1
{
publicstaticvoidmain(String[]args)
{
if(args.length!=3)
{
System.err.println("輸入的參數個數不是3個");
return;
}
try
{
Scannerinput=newScanner(newFile(args[0]));
int[]a=Test.readfile(input);
input=newScanner(newFile(args[1]));
int[]b=Test.readfile(input);
int[]dest=Test.merge(a,b);
try
{
PrintStreamoutput=newPrintStream(args[2]);
Test.writefile(output,dest);
}
catch(FileNotFoundExceptione)
{
e.printStackTrace();
}
}
catch(FileNotFoundExceptione)
{
e.printStackTrace();
}
}
}

classTest2
{
publicstaticvoidmain(String[]args)
{
if(args.length!=1)
{
System.err.println("輸入的參數個數不是1個");
return;
}
try
{
Scannerinput=newScanner(newFile(args[0]));
int[]dest=Test.readfile(input);
Arrays.sort(dest);
PrintStreamoutput=newPrintStream(args[0]);
Test.writefile(output,dest);
}
catch(FileNotFoundExceptione)
{
e.printStackTrace();
}
}
}

<Test3>
{
inti;

publicTest3(inti)
{
this.i=i;
}

@Override
publicintcompareTo(Test3o)
{
if(o.i>i)
{
return-1;
}
elseif(o.i<i)
{
return1;
}
else
{
return0;
}
}

@Override
publicStringtoString()
{
returnString.format("%s",i);
}

publicstaticvoidmain(String[]args)
{
if(args.length!=3)
{
System.err.println("輸入的參數個數不是3個");
return;
}
LinkedList<Test3>list=newLinkedList<Test3>();
try
{
Scannerinput1=newScanner(newFile(args[0]));
Scannerinput2=newScanner(newFile(args[1]));
while(true)
{
try
{
inta=Integer.parseInt(input1.nextLine().trim());
intb=Integer.parseInt(input2.nextLine().trim());
Test3ta=newTest3(a);
Test3tb=newTest3(b);
list.add(ta);
list.add(tb);
}
catch(Exceptione)
{
break;
}
}
input1.close();
input2.close();
Collections.sort(list);
PrintStreamoutput=newPrintStream(args[2]);
output.append(list.toString().replaceAll("[\[\]\s]","").replaceAll(",",Test.LINE));
output.flush();
output.close();
}
catch(FileNotFoundExceptione)
{
e.printStackTrace();
}
}
}

⑸ Java中通過txt文件存儲和取出數據

如果是這樣的話,你就先用string的split方法以,為分隔符號分開,再replace「」,這兩個東東就可以得到你要的中間的數據了。有個缺點比較佔用內存,或許你也可以去讀文件讀到,的時候就將之前的存起來,然後再讀下面的東西。思路而已試試看吧~

⑹ JAVA 查找TXT文件內容!!

找不到S開頭的字元???這句話是什麼意思?什麼叫S開頭的字元,一個字母就是一個字元。。

⑺ java怎樣實現讀寫TXT文件

主要有用到java原生態的Io類,沒有第三個包。直接上代碼:

importjava.io.*;

publicclasswrite{
publicstaticvoidmain(String[]args){
write("E://123.txt","hello");
}

publicstaticvoidwrite(Stringpath,Stringcontent){
try{
Filef=newFile(path);

if(f.exists()){
System.out.println("文件存在");
}else{
System.out.println("文件不存在,正在創建...");
if(f.createNewFile()){
System.out.println("文件創建成功!");
}else{
System.out.println("文件創建失敗!");
}
}
BufferedWriteroutput=newBufferedWriter(newFileWriter(f));
output.write(content);
output.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}

⑻ java中如何調用txt里的數據

創建一個數據讀取流

下面是一個把圖片存到資料庫的例子,你可以參考一下:

public class FileUtil {
private static Log log = LogFactory.getLog(FileUtil.class);

//將文件對象轉換為二進制位元組數組
public static byte[] toByteArray(File photo) throws IOException {
//獲得文件對象的輸入流
FileInputStream fis = new FileInputStream(photo);
BufferedInputStream bis = new BufferedInputStream(fis);

//位元組數組的輸出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c = bis.read();
while (c != -1) {
baos.write(c);
c = bis.read();
}
bis.close();
byte[] rtn = baos.toByteArray();
baos.close();
return rtn;
}

/**
* 構建小樣圖片
* @param srcFile
* @return
*/
public static byte[] buildThumbnail(File srcFile) {
byte[] rtn = null;
try {
Image src = ImageIO.read(srcFile); // 構造Image對象
int oldWidth = src.getWidth(null); // 得到源圖寬
int oldHeight = src.getHeight(null);// 得到源圖高

log.debug("old width is " + oldWidth);
log.debug("old height is " + oldHeight);

float divWidth = 200f; // 限制寬度為200
int newWidth = 200; // 縮略圖寬,
int newHeight = 0; // 縮略圖高
float tmp;//縮略比例
if (oldWidth > newWidth) {
tmp = oldWidth / divWidth;
newWidth = Math.round(oldWidth / tmp);// 計算縮略圖高
newHeight = Math.round(oldHeight / tmp);// 計算縮略圖高
log.debug("tmp scale is " + tmp);
} else {
newWidth = oldWidth;
newHeight = oldHeight;
}

//繪制的圖片默認大小
int imageHeight = 100;
int imageWidth = 200;

log.debug("new width is " + newWidth);
log.debug("new height is " + newHeight);

BufferedImage bufferedImage = new BufferedImage(newWidth,
newHeight, BufferedImage.TYPE_INT_RGB);

Graphics2D graphics2D = (Graphics2D) bufferedImage.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.clearRect(0, 0, imageWidth, imageHeight);

//繪制新的圖片對象
bufferedImage.getGraphics().drawImage(src,
//(imageWidth - oldWidth) / 2, (imageHeight - newHeight) / 2,
0,0,
newWidth, newHeight, null); // 繪制縮小後的圖

ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bufferedImage); // 進行JPEG編碼
rtn = baos.toByteArray();
bos.close();
baos.close();
} catch (Exception e) {
log.debug(e);
} finally {

}
return rtn;
}
}

⑼ 求java操作txt文件的方法

第一個就是按行讀取,調用 BufferedReader 的 readLine() 方法,當讀到第 n 行時打斷循環,返回該行;
第二個,要是我做的話,就把第 n 行換掉,然後全部回寫到txt文件里

熱點內容
單片機android 發布:2024-09-20 09:07:24 瀏覽:762
如何提高三星a7安卓版本 發布:2024-09-20 08:42:35 瀏覽:661
如何更換伺服器網站 發布:2024-09-20 08:42:34 瀏覽:309
子彈演算法 發布:2024-09-20 08:41:55 瀏覽:286
手機版網易我的世界伺服器推薦 發布:2024-09-20 08:41:52 瀏覽:815
安卓x7怎麼邊打游戲邊看視頻 發布:2024-09-20 08:41:52 瀏覽:160
sql資料庫安全 發布:2024-09-20 08:31:32 瀏覽:91
蘋果連接id伺服器出錯是怎麼回事 發布:2024-09-20 08:01:07 瀏覽:505
編程鍵是什麼 發布:2024-09-20 07:52:47 瀏覽:655
學考密碼重置要求的證件是什麼 發布:2024-09-20 07:19:46 瀏覽:479