包含java出力txt的词条
本篇文章给大家谈谈java出力txt,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
Java中怎么写数据输出为.txt格式的文件
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class TestBaiduKnow {
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
在D盘新建两个文件test.txt,test1.txt
把内容拷到test中,test1为输出。。。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class ZhiDao {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = null;
String lineContent = null;
StringBuffer sb = new StringBuffer();
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader("D:\\test.txt"));
pw = new PrintWriter("D:\\test1.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while ((lineContent = br.readLine()) != null) {
if(lineContent.equals("")){
sb.append("\r\n");
sb.append("\r\n");
}else{
for(int i = 0; ilineContent.length(); i++){
char charContent = lineContent.charAt(i);
sb.append(charContent);
if(i != 0 i%60 == 0){
sb.append("\r\n");
}
}
}
}
System.out.println(sb);
pw.write(sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如何用java输出txt文件
输入无需使用字节流,直接字符流读取即可。
private void input(String fileName) throws IOException {
try(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while((line=reader.readLine()) != null) {
System.out.println(line);
}
}
}
同样输出,只要把Input换成Output;
private void output(String fileName, String content) throws IOException{
try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content);
writer.flush();
}
}
如何用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和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。
发布于:2022-11-28,除非注明,否则均为
原创文章,转载请注明出处。