本文目錄一覽:
Java中怎麼將字符串按行寫入到txt文件中
java寫入文本文件的方法很多,比如FileWriter
FileWriter fw = new FileWriter(“D:/Test.txt”);
String s = “hello world\n”;
fw.write(s,0,s.length());
s = “hello world2\n”;
fw.write(s,0,s.length());
fw.flush();
這樣就寫了兩行了。其中斜線n是換行符
java代碼 如何向TXT文件寫入內容?
向txt文件寫入內容基本思路就是獲得一個file對象,新建一個txt文件,打開I/O操作流,使用寫入方法進行讀寫內容,示例如下:
package common;
import java.io.*;
import java.util.ArrayList;
public class IOTest {
public static void main (String args[]) {
ReadDate();
WriteDate();
}
/**
* 讀取數據
*/
public static void ReadDate() {
String url = “e:/2.txt”;
try {
FileReader read = new FileReader(new File(url));
StringBuffer sb = new StringBuffer();
char ch[] = new char[1024];
int d = read.read(ch);
while(d!=-1){
String str = new String(ch,0,d);
sb.append(str);
d = read.read(ch);
}
System.out.print(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 寫入數據
*/
public static void WriteDate() {
try{
File file = new File(“D:/abc.txt”);
if (file.exists()) {
file.delete();
}
file.createNewFile();
BufferedWriter output = new BufferedWriter(new FileWriter(file));
ArrayList ResolveList = new ArrayList();
for (int i = 0; i 10; i++) {
ResolveList.add(Math.random()* 100);
}
for (int i=0 ;i
output.write(String.valueOf(ResolveList.get(i)) + “\n”);
}
output.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
原文出自【比特網】,轉載請保留原文鏈接:
java如何從數據庫讀取數據並寫入txt文件?
寫Java程序時經常碰到要讀如txt或寫入txt文件的情況,但是由於要定義好多變量,經常記不住,每次都要查,特此整理一下,簡單易用,方便好懂!
[java] view plain copy
package edu.thu.keyword.test;
import java.io.File;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
public class cin_txt {
static void main(String args[]) {
try { // 防止文件建立或讀取失敗,用catch捕捉錯誤並打印,也可以throw
/* 讀入TXT文件 */
String pathname = “D:\\twitter\\13_9_6\\dataset\\en\\input.txt”; // 絕對路徑或相對路徑都可以,這裡是絕對路徑,寫入文件時演示相對路徑
File filename = new File(pathname); // 要讀取以上路徑的input。txt文件
InputStreamReader reader = new InputStreamReader(
new FileInputStream(filename)); // 建立一個輸入流對象reader
BufferedReader br = new BufferedReader(reader); // 建立一個對象,它把文件內容轉成計算機能讀懂的語言
String line = “”;
line = br.readLine();
while (line != null) {
line = br.readLine(); // 一次讀入一行數據
}
/* 寫入Txt文件 */
File writename = new File(“.\\result\\en\\output.txt”); // 相對路徑,如果沒有則要建立一個新的output。txt文件
writename.createNewFile(); // 創建新文件
BufferedWriter out = new BufferedWriter(new FileWriter(writename));
out.write(“我會寫入文件啦\r\n”); // \r\n即為換行
out.flush(); // 把緩存區內容壓入文件
out.close(); // 最後記得關閉文件
} catch (Exception e) {
e.printStackTrace();
}
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/241008.html