導航:首頁 > 編程語言 > java輸出txt文件

java輸出txt文件

發布時間:2022-08-27 06:07:04

A. java中輸出txt文件

不清楚樓主具體是哪裡不懂,先給個大概思路,後台也就是action或servlet中利用java.io包把文本讀出來,然後setAttribute()到頁面上去,頁面上textarea取set進去的值就ok了
寫文件大同小異,流程相反
附上io的一個例子
final int BUFFER_LENGTH=1024;

public void formatFlie(String fileName) {
char[] c=new char[BUFFER_LENGTH];//buffered area
String inStr="";//read String
try {
BufferedReader readBuff=new BufferedReader(new FileReader(fileName));
while(readBuff.read(c,0,BUFFER_LENGTH)!=-1) {
//System.out.println("pos:"+read_pos);
for(int i=0;i<BUFFER_LENGTH;i++)
inStr+=c[i];
}

System.out.println(inStr);
readBuff.close();
}
catch(IOException e)
{
System.out.println(e.toString());
}

}

B. 如何用java輸出txt文件

輸入無需使用位元組流,直接字元流讀取即可。

privatevoidinput(StringfileName)throwsIOException{
try(BufferedReaderreader=newBufferedReader(newFileReader(fileName))){
Stringline;
while((line=reader.readLine())!=null){
System.out.println(line);
}
}
}

同樣輸出,只要把Input換成Output;

privatevoidoutput(StringfileName,Stringcontent)throwsIOException{
try(BufferedWriterwriter=newBufferedWriter(newFileWriter(fileName))){
writer.write(content);
writer.flush();
}
}

C. 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");

}

}

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

E. Java讀取TXT文件並且輸出~請各位大俠解答。小弟拜謝

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Scanner;

publicclassReader{

publicstaticvoidmain(String[]args)throwsFileNotFoundException{
Scannerin=newScanner(newFile("dataIn.txt"));
Stringline;
//每次讀取一行
List<String>result=newArrayList<String>();
while(in.hasNextLine()){
line=in.nextLine();
Stringstr[]=line.split(";");
result.add(str[1].split("=")[1]);
}


FiledataOut=newFile("dataOut.txt");
PrintWriterpw=newPrintWriter(dataOut);
for(Stringb:result){
System.out.println(b);
pw.println(b);
}
pw.close();
}

}

F. java輸出到TXT文件時怎麼加換行

java輸出到txt的時候增加換行符的方法如下:
package
com.anjoyo.test;
import
java.io.FileWriter;
import
java.io.IOException;
public
class
TestFileWriter
{
public
static
void
main(String[]
args)
throws
IOException{
//\r\n為換行符
FileWriter
fw
=
new
FileWriter("D:\\1.txt");
//寫入第一行換行
fw.write("第一行\r\n");
//或者獲得系統換行符
String
str
=
"第二行"
+
System.getProperty("line.separator");
fw.write(str);
fw.write("第三行");
fw.close();
/*
*
windows下的文本文件換行符:\r\n
linux/unix下的文本文件換行符:\r
*
Mac下的文本文件換行符:\n
*/
}
}

G. JAVA如何調用txt文件 並用txt列印輸出結果

import java.io.*;
public class Start
{
public void readAndRead()
{
try
{
FileReader fr = new FileReader("need.txt");//需要讀取的文件路徑
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
while(s!=null)//如果當前行不為空
{
System.out.println(s);//列印當前行
s= br.readLine();//讀取下一行
}
br.close();//關閉BufferReader流
fr.close(); //關閉文件流
}catch(IOException e)//捕捉異常
{
System.out.println("指定文件不存在");//處理異常
}
}
public static void main(String [] args)
{
Start start = new Start();
start.readAndRead();
}
}

H. java生成txt文件 急急急!!!

package file;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/** 用FileOutputStream類往指定文件中寫入數據 */
public class FileOutputStreamTest {
public static void main(String[] args) {
FileOutputStream out = null;
try {
//step1: 創建一個向指定名的文件中寫入數據的FileOutputStream
//第二個參數設置為true表示:使用追加模式添加位元組
out = new FileOutputStream("D:\\IOTest\\dest.txt",true);
//step2: 寫數據
out.write('#');
out.write("helloWorld".getBytes());
out.write("你好".getBytes());
out.write("\r\n".getBytes());//換行
out.write("網路新浪".getBytes());

//step3: 刷新此輸出流
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) { // 捕獲IO異常
e.printStackTrace();
}finally{
if(out != null){
try {
out.close(); //step4: 關閉輸出流
} catch (IOException e) {
e.printStackTrace();
} } } }}

給你看看我寫的 參考下吧

I. 怎麼將一個java程序的結果輸出到文本文檔中,寫一段代碼,謝謝

importjava.io.BufferedWriter;
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.util.Scanner;


publicclassOutToTxt{
;
privatestaticScannersc;

publicstaticvoidmain(String[]args){
Fileout=newFile("./Out.txt");
if(!out.exists()){
try{
out.createNewFile();
}catch(IOExceptione){
e.printStackTrace();
}
}
try{
writer=newBufferedWriter(newFileWriter(out));
}catch(IOExceptione){
e.printStackTrace();
}

sc=newScanner(System.in);
System.out.println("請輸入文本內容,輸入exit結束:");
try{
writer.write("");//清空文本
Stringsplit="";
while(true){
Stringline=sc.nextLine();
if(line.equalsIgnoreCase("exit")){
break;
}
writer.append(split+line);
split=" ";
}
}catch(IOExceptione1){
e1.printStackTrace();
}finally{
if(null!=writer){
try{
writer.flush();
writer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

}

你可以運行後輸入

Hello World!

This is my first application.

exit

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

}
}
//簡單的一個例子,來模擬輸出

閱讀全文

與java輸出txt文件相關的資料

熱點內容
編譯原理代碼在哪裡運行 瀏覽:584
解密攝影pdf 瀏覽:72
演算法編程中級題目 瀏覽:249
c語言編譯器畢業設計 瀏覽:715
醫保卡申請app哪個好 瀏覽:944
阿里雲伺服器上傳源碼 瀏覽:602
營銷管理科特勒pdf 瀏覽:696
願望清單app哪個好 瀏覽:459
安卓外放聲音怎麼解決 瀏覽:195
脈脈app干什麼用的 瀏覽:360
拽姐是哪個app 瀏覽:860
雲伺服器刪除了還有嗎 瀏覽:234
macbook可以用單片機嘛 瀏覽:309
南陽php招聘 瀏覽:817
去哪裡找按摩師很漂亮的app 瀏覽:821
86x99用簡便演算法計算 瀏覽:833
php截圖flash 瀏覽:276
卸載聯想app哪個好 瀏覽:722
php文字轉圖片 瀏覽:332
豆客後台怎麼加密碼 瀏覽:577