当前位置:首页 » 编程语言 » 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文件里

热点内容
数据库一键安装 发布:2025-05-01 14:47:28 浏览:18
人生苦短我用python梗 发布:2025-05-01 14:44:12 浏览:722
房车水电配置需要什么 发布:2025-05-01 14:42:38 浏览:494
linux主设备号从设备号 发布:2025-05-01 14:41:44 浏览:784
实现一个简易的编译器 发布:2025-05-01 14:35:48 浏览:879
vivo如何关闭qq隐私密码锁 发布:2025-05-01 14:28:27 浏览:505
宇视监控怎么配置国际编码 发布:2025-05-01 14:26:55 浏览:824
安卓如何改变手机版本 发布:2025-05-01 14:25:57 浏览:775
android外国 发布:2025-05-01 14:25:55 浏览:782
数据库上亿数据 发布:2025-05-01 14:18:31 浏览:582