導航:首頁 > 編程語言 > 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相關的資料

熱點內容
帶著智能手機闖盪異世界 小說 瀏覽:901
男同情愛電影 瀏覽:913
vb監控文件夾 瀏覽:850
台灣丈夫電影 瀏覽:660
戴爾筆記本為什麼連不上無線網路 瀏覽:582
台灣的電影電視劇都用什麼網站 瀏覽:238
米思齊編程土壤濕度感測器怎麼用 瀏覽:208
大寸度愛情電影 瀏覽:213
2015年全球大數據總量 瀏覽:63
建設工程人員配置要求在哪個文件 瀏覽:157
泰國大尺度同性 瀏覽:448
手機excel怎麼保存文件怎麼打開 瀏覽:77
主角叫林白 瀏覽:395
胸很大的電影 瀏覽:899
水裡作愛的電影韓國 瀏覽:404
京東金融java薪酬 瀏覽:205
mastercam91安裝教程 瀏覽:119
ie6翻書js 瀏覽:148
干凈的電影網 瀏覽:756
不收費的電視劇網站 瀏覽:947

友情鏈接