导航:首页 > 编程语言 > java输出string到txt

java输出string到txt

发布时间:2021-12-05 07:18:23

A. java把string输出到txt,如何先把原有内容全部清空再输出

直接写就行,就清空了。
如果要接着写在用stream或者reader的时候需要加一个参数true。

B. java写入字符串到txt文件

我来帮楼主解决一下这个问题:
【问题叙述】
在使用writeUTF(String str)这个方法之前最好调用writeShort(int inv)方法将一个 short 值以 2-byte 值形式写入基础输出流中,先写入高字节的方式,避免丢失字符。
代码演示】
import java.io.*;
public class FileTest
{
public static void main(String [] args)
{
try {
FileWriter fw = new FileWriter("b.txt");
File f = new File("b.txt");
int[] a = new int[]{1, 2, 3};
for (int i = 0; i < a.length; i++) {
fw.write(String.valueOf(a[i]));
}

FileOutputStream os = new FileOutputStream(f);
DataOutputStream out = new DataOutputStream(os);
out.writeShort(2);
out.writeUTF("uuxuxuing");
System.out.println(out);
fw.flush();
fw.close();
System.out.println(fw);
} catch (Exception e) {
}

}

}
比如以上代码,楼主可以参考,运行后发现再不会丢失字符的情况出现。
【第二个问题】
关于第二个问题,你可以这么简单理解,产生问题的出现是因为过早关闭了fw,你可以这样改一下程序,就可以分析出缘由:
import java.io.*;
public class FileTest
{
public static void main(String [] args)
{
try {
FileWriter fw = new FileWriter("b.txt");
File f = new File("c.txt"); //这里修改
int[] a = new int[]{1, 2, 3};
for (int i = 0; i < a.length; i++) {
fw.write(String.valueOf(a[i]));
}
fw.flush();//放到前面了
fw.close();
FileOutputStream os = new FileOutputStream(f);
DataOutputStream out = new DataOutputStream(os);
out.writeShort(2);
out.writeUTF("uuxuxuing");
System.out.println(out);

System.out.println(fw);
} catch (Exception e) {
}

}

}
你会发现b.txt中完整输出了123,而在c.txt中没有完整输出123,只是输出了字符串,可以看出,在FileWrite方法成功执行输出了123,而他正准备输出后面的字符串之前被关闭了,所以他只输出了123,而File通过输出流成功输出了字符串(在关闭FileWrite之后),但是他并不知道关闭之前的FileWrite干了哪些事情,所以他的输出只能是乱码(因为关闭了,所以他不知道FileWrite干了哪些事)
【建议】如果要往文件里写些东西的话,这样做比较整齐也简单一点:
import java.io.*;
class ReaderTest
{
public static void main(String [] args)throws Exception
{
FileOutputStream fos=new FileOutputStream("a.txt");
OutputStreamWriter osw=new OutputStreamWriter(fos);
BufferedWriter bw=new BufferedWriter(osw);
bw.write("您好!");
bw.close();

FileInputStream fis=new FileInputStream("a.txt");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
System.out.println(br.readLine());
br.close();
}
}
说明:为了简便,我用throws代替了try...catch,并不是没有异常,这段代码是正确的,楼主可以运行看下效果。
希望我的回答能对楼主有所帮助!

C. java实现将结果输出到txt

遍历所有数组,然后用FileInputStream()
FileOutputStream fos = new FileOutputStream("d://data.txt",true);

D. java 数据输出到txt文件

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class TestBaiKnow {

public static void main(String[] args) throws IOException {
FileOutputStream fs = new FileOutputStream(new File("D:\\text.txt"));
PrintStream p = new PrintStream(fs);
p.println(100);
p.close();

}
}
//简单的一个例子,来模拟输出

E. java如何把字符串的内容保存到某位置的txt里

通过scanner对象进行写入,以下是定义的方法,直接调用即可
publicwriteStrToFile(Stringstr,Stringpath)//要写入的字符串,要写入的文件路径
{
Scannerinput=newScanner(str+" ");
FileOutputStreamfos=newFileOutputStream(path);
while(input.hasNext()){
Stringa=input.next();
fos.write((a+" ").getBytes());
}
fos.close();
input.close();
}

F. java编程 如何将println输出的内容写入到txt文本中

如果你从命令行运行,那么可以java fencisuanfa > out.txt

否则可版以用

BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"));
把 System.out.println(line);
改成权
out.write(line+"\n")

G. JAVA 如何输出数据到TXT文件内

package test;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

public class ReadColorTest {
/**
* 读取一张图片的RGB值
*
* @throws Exception
*/
public void getImagePixel(String image) throws Exception {
File fileCar = new File("D:\\car.txt");
FileOutputStream fos = new FileOutputStream(fileCar);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int[] rgb = new int[3];
File file = new File(image);
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (Exception e) {
e.printStackTrace();
}
int width = bi.getWidth();
int height = bi.getHeight();
int minx = bi.getMinX();
int miny = bi.getMinY();
System.out.println("width=" + width + ",height=" + height + ".");
bos.write(("width=" + width + ",height=" + height + ".\n").getBytes());
System.out.println("minx=" + minx + ",miniy=" + miny + ".");
bos.write(("minx=" + minx + ",miniy=" + miny + ".\n").getBytes());
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j); // 下面三行代码将一个数字转换为RGB数字
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
System.out.println("i=" + i + ",j=" + j + ":(" + rgb[0] + ","+ rgb[1] + "," + rgb[2] + ")");
bos.write(("i=" + i + ",j=" + j + ":(" + rgb[0] + ","+ rgb[1] + "," + rgb[2] + ")\n").getBytes());
}
}
}

/**
* 返回屏幕色彩值
*
* @param x
* @param y
* @return
* @throws AWTException
*/
public int getScreenPixel(int x, int y) throws AWTException { // 函数返回值为颜色的RGB值。
Robot rb = null; // java.awt.image包中的类,可以用来抓取屏幕,即截屏。
rb = new Robot();
Toolkit tk = Toolkit.getDefaultToolkit(); // 获取缺省工具
Dimension di = tk.getScreenSize(); // 屏幕尺寸规格
System.out.println(di.width);
System.out.println(di.height);
Rectangle rec = new Rectangle(0, 0, di.width, di.height);
BufferedImage bi = rb.createScreenCapture(rec);
int pixelColor = bi.getRGB(x, y);

return 16777216 + pixelColor; // pixelColor的值为负,经过实践得出:加上颜色最大值就是实际颜色值。
}

/**
* @param args
*/
public static void main(String[] args) throws Exception {
int x = 0;
ReadColorTest rc = new ReadColorTest();
x = rc.getScreenPixel(100, 345);
System.out.println(x + " - ");
rc.getImagePixel("D:\\car.jpg");

}

}

H. 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();
}
}

I. java中如何将输出结果到txt文件中

FileWriter\ PrintWriter 和 System.out.println() 相同的使用方法了

~~~~

阅读全文

与java输出string到txt相关的资料

热点内容
软件编程有哪些 浏览:510
win7镜像文件下载gho 浏览:177
数据库的含义及特征 浏览:402
道道通配置文件 浏览:938
javascript字符相加 浏览:590
extjs4入门 浏览:684
网上修改wifi密码 浏览:903
有哪些图书数据库 浏览:445
u盘删除的文件 浏览:179
机床的操作系统编程难在哪里 浏览:243
springboot多文件上传 浏览:767
securecrt传输文件 浏览:21
有哪些好的跑步app 浏览:36
win10易升无限重启 浏览:460
投资app平台有哪些 浏览:192
开发板tftp下载文件夹 浏览:310
什么app可以测脸型 浏览:722
happytogether朴海镇 浏览:101
iphone6己越狱升84好不 浏览:326
下载全民k歌389版本 浏览:323