导航:首页 > 编程语言 > java的文件输入输出

java的文件输入输出

发布时间:2022-05-25 12:05:09

java如何从文件输入输出

// 读取文件
public class ReadTextFileExample {
public static void main(String[] args ) {
File file = new File("d:\\caipiao_3.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;

try {
reader = new BufferedReader(new FileReader(file));
String text = null;

// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text).append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}

// show file contents here
System.out.println(contents.toString());
}
}
// 写出文件
public class WriteTextFileExample {
public static void main(String[] args ) {
FileOutputStream fos = null;
BufferedWriter bw = null;
try {
File file = new File("abc.txt");
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("this is a sample!");
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (bw != null)
bw.close();
if (fos != null)
fos.close();
}
catch (IOException ie) {
}
}
}
}

② Java中如何实现文件的输入输出

程序如下:
<span style="color:#990000;">

</span>File file1 = new File("/home/a123/a");

if (file1.exists()) {
System.out.println("存在文件夹a");
} else {
file1.mkdir(); // 文件夹的创建 创建文件夹/home/a123/a
}
File file2 = new File("/home/a123/a/test");
if (file2.exists()) {
System.out.println("存在文件夹或者文件test");
} else {
try {
file2.createNewFile(); // 文件的创建,注意与文件夹创建的区别
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 最简单的文件读写方法是使用类FileWriter
* (它的父类依次是java.io.OutputStreamWriter——>java.io.Writer——>java.lang.Object );
*/

// 下面是向文件file2里面写数据
try {
FileWriter fileWriter = new FileWriter(file2);
String s = new String("This is a test! \n" + "aaaa");
fileWriter.write(s);
fileWriter.close(); // 关闭数据流

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/*
* 这样写数据的话,是完全更新文件test里面的内容,即把以前的东西全部删除,重新输入。
* 如果不想删除以前的数据,而是把新增加的内容增添在文件末尾处。只需要在创建FileWriter对象时候,使用另外一个构造函数即可:
* FileWriter fileWriter=new FileWriter(file2,true);
*/

// 下面是从文件file2读东西
try {
FileReader fileReader = new FileReader(file2);
String s = null;
char ch;
try {
char[] c = new char[100];
fileReader.read(c,0,2); // 具体想得到文件里面的什么值(单个char?int?还是String?),
System.out.println(c);
fileReader.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 具体想得到文件里面的什么值(单个char?int?还是String?),需要知道不通read的不同用法:
* 1. int read() 读取单个字符。
* 2. int read(char[] cbuf) 将字符读入数组。 可以再将字符型数组转化位字符串
* 3. int read(char[] cbuf,int off,int len) 将字符读入数组的某一部分。
* 这三个方法都返回一个int值,作用是:读取的字符数,如果已到达流的末尾,则返回 -1.
*/

}

③ java的输入输出中,如果数据相对于外部文件是出去了,我们称之为输出操作对吗

不是的,输入/输出是相对于程序说的。把数据传递给程序的变量,就是输入;把程序变量的值,发出去(给显示器或者文件),就是输出。

④ java实现文件的输入输出的主要使用的类是什么

ava的输入输出功能来自java.io 包中的InputStream类、OutputStream类、Reader类和Writer类以及继承它们的各种子类。

⑤ java输入文件名,输出该文件的内容

java读取文件的内容,使用BufferedReader来读取,通过Scanner对象获取输入的文件名,来读取这个文件的内容并输出,具体示例代码如下:

publicclasstxttest{
/**
*读取txt文件的内容
*@paramfile想要读取的文件对象
*@return返回文件内容
*/
publicstaticStringtxt2String(Filefile){
Stringresult="";
try{
BufferedReaderbr=newBufferedReader(newFileReader(file));//构造一个BufferedReader类来读取文件
Strings=null;
while((s=br.readLine())!=null){//使用readLine方法,一次读一行
result=result+" "+s;
}
br.close();
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}

publicstaticvoidmain(String[]args){
Scannerscan=newScanner(System.in);
System.out.println("请输入文件名:");
Stringstr=scan.next();
Stringmulu="C:\Users\hp\Desktop\"+str+".txt";//文件具体目录
Filefile=newFile(mulu);
System.out.println(txt2String(file));
}
}

⑥ java中读入和输出文本文件

/**
*测试3:从文本文件中读取数据
*/
staticvoidtestExample03(){
//1、在内存中打开要读取文件的字符流对象
try{
Readerreader=newFileReader("e:/ReadMe.log");
//2、从字符流中读取数据
//一次读取一个字符(麻烦)
/*intnum=reader.read();
System.out.println((char)num);
num=reader.read();
System.out.println((char)num);*/
//一次读取一个数组(必须确定数组的长度)
/*char[]cbuf=newchar[10];
reader.read(cbuf);
System.out.println(newString(cbuf));*/
//循环读取,一次就读一个
intch=reader.read();
StringBufferbuffer=newStringBuffer();
while(ch!=-1){//读取成功
buffer.append((char)ch);
ch=reader.read();
}
System.out.println(buffer.toString());
//3、关闭流
reader.close();
}catch(FileNotFoundExceptione){
System.out.println("要读取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件读取错误:"+e.getMessage());
}
}
/**
*测试4:向文本文件中写入数据
*/
staticvoidtestExample04(){
System.out.println("请输入内容:");
Stringtext=input.next();
try{
//1、打开流
Writerw=newFileWriter("e:/测试.txt",true);
//2、写入内容
w.write(text);
//3、关闭流
w.close();
}catch(IOExceptione){
System.out.println("文件写入错误:"+e.getMessage());
}
}
/**
*测试5:使用效率高的字符流读写数据
*/
staticvoidtestExample05(){
try{
//1、创建流对象
Readerreader=newFileReader("e:/ReadMe.log");
//构建高效流对象
BufferedReaderbuffReader=newBufferedReader(reader);

//2、读取一行字符串
Stringline=buffReader.readLine();
StringBufferbuffer=newStringBuffer();
while(line!=null){
buffer.append(line+" ");
line=buffReader.readLine();
}
System.out.println(buffer.toString());;
//3、关闭流
buffReader.close();
reader.close();

Writerw=newFileWriter("e:/NewReadMe.txt");
BufferedWriterbuffWriter=newBufferedWriter(w);

buffWriter.write(buffer.toString());

buffWriter.close();
w.close();
System.out.println("写入成功!");

}catch(FileNotFoundExceptione){
System.out.println("要读取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件读取错误:"+e.getMessage());
}
}

⑦ java怎么输出

java控制台输出由print( ) 和 println( )来完成最为简单。这两种方法由rintStream(System.out引用的对象类型)定义。尽管System.out是一个字节流,用它作为简单程序的输出是可行的。因为PrintStream是从OutputStream派生的输出流,它同样实现低级方法write(),write()可用来向控制台写数据。PrintStream 定义的write( )的最简单的形式如下:

void write(int byteval)

该方法按照byteval指定的数目向文件写字节。尽管byteval 定义成整数,但只有低位的8个字节被写入。下面的短例用 write()向屏幕输出字符“A”,然后是新的行。

// Demonstrate System.out.write().

class WriteDemo {

public static void main(String args[]) {

int b;

b = 'A';

System.out.write(b);

System.out.write(' ');

}

}

一般不常用write()来完成向控制台的输出(尽管这样做在某些场合非常有用),因为print()和println() 更容易用。

四、PrintWriter类

尽管Java允许用System.out向控制台写数据,但建议仅用在调试程序时或在例程中。对于实际的程序,Java推荐的向控制台写数据的方法是用PrintWriter流。PrintWriter是基于字符的类。用基于字符类向控制台写数据使程序更为国际化。PrintWriter定义了多个构造函数,这里所用到的一个如下:

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

outputStream是OutputStream类的对象,flushOnNewline控制Java是否在println()方法被调用时刷新输出流。如果flushOnNewline为true,刷新自动发生,若为false,则不发生。

PrintWriter支持所有类型(包括Object)的print( )和println( )方法,这样,就可以像用ystem.out那样用这些方法。如果遇到不同类型的情况,PrintWriter方法调用对象的toString()方法并打印结果。用PrintWriter向外设写数据,指定输出流为System.out并在每一新行后刷新流。例如这行代码创建了与控制台输出相连的PrintWriter类。

PrintWriter pw = new PrintWriter(System.out, true);

下面的应用程序说明了用PrintWriter处理控制台输出的方法:

// Demonstrate PrintWriter

import java.io.*;

public class PrintWriterDemo {

public static void main(String args[]) {

PrintWriter pw = new PrintWriter(System.out, true);

pw.println("This is a string");

int i = -7;

pw.println(i);

double d = 4.5e-7;

pw.println(d);

}

}

该程序的输出如下:

This is a string

-7

4.5E-7

⑧ java文件输入输出

import java.util.*;
import java.io.*;
class Student {
private String name;
private int age;
private int javaScore;
private int cScore;

public Student(String name,int age) {
this.name = name;
this.age = age;
}

public void setJavaScore(int java) {
if(java < 101 && java >= 0) {
this.javaScore = java;
}else{
System.out.println("Wrong score !");
}

}

public int getJavaScore() {
return this.javaScore;
}

public void setCScore(int C) {
if(C < 101 && C >= 0) {
this.cScore = C;
}else{
System.out.println("Wrong score !");
}

}

public int getCScore() {
return this.cScore;
}

public String toString() {
return this.name+" "+this.age+" "+this.javaScore+" "+this.cScore+"\n";
}
}
class TestChengji {
public static void main(String [] args) throws Exception{
Student[] StudentInfo = new Student[3];
Scanner in = new Scanner(System.in);
System.out.println("请输入学生姓名 年龄 c语言成绩与java的成绩,中间用空格隔开:");
System.out.println("例如: 小明 18 82 80");
for(int i=0;i<3;i++) {
System.out.println("请输入数据:");
StudentInfo[i] = new Student(in.next(),in.nextInt());
StudentInfo[i].setCScore(in.nextInt());
StudentInfo[i].setJavaScore(in.nextInt());
}
in.close();
BufferedWriter writer = new BufferedWriter(new FileWriter("chengji.txt"));
for(int i=0;i<3;i++) {
writer.write(StudentInfo[i].toString());
writer.flush();
}
writer.close();
}
}
//试试

⑨ Java中如何实现文件的输入和输出

程序如下:
<span style="color:#990000;">

</span>File file1 = new File("/home/a123/a");

if (file1.exists()) {
System.out.println("存在文件夹a");
} else {
file1.mkdir(); // 文件夹的创建 创建文件夹/home/a123/a
}
File file2 = new File("/home/a123/a/test");
if (file2.exists()) {
System.out.println("存在文件夹或者文件test");
} else {
try {
file2.createNewFile(); // 文件的创建,注意与文件夹创建的区别
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 最简单的文件读写方法是使用类FileWriter
* (它的父类依次是java.io.OutputStreamWriter——>java.io.Writer——>java.lang.Object );
*/

// 下面是向文件file2里面写数据
try {
FileWriter fileWriter = new FileWriter(file2);
String s = new String("This is a test! \n" + "aaaa");
fileWriter.write(s);
fileWriter.close(); // 关闭数据流

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/*
* 这样写数据的话,是完全更新文件test里面的内容,即把以前的东西全部删除,重新输入。
* 如果不想删除以前的数据,而是把新增加的内容增添在文件末尾处。只需要在创建FileWriter对象时候,使用另外一个构造函数即可:
* FileWriter fileWriter=new FileWriter(file2,true);
*/

// 下面是从文件file2读东西
try {
FileReader fileReader = new FileReader(file2);
String s = null;
char ch;
try {
char[] c = new char[100];
fileReader.read(c,0,2); // 具体想得到文件里面的什么值(单个char?int?还是String?),
System.out.println(c);
fileReader.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 具体想得到文件里面的什么值(单个char?int?还是String?),需要知道不通read的不同用法:
* 1. int read() 读取单个字符。
* 2. int read(char[] cbuf) 将字符读入数组。 可以再将字符型数组转化位字符串
* 3. int read(char[] cbuf,int off,int len) 将字符读入数组的某一部分。
* 这三个方法都返回一个int值,作用是:读取的字符数,如果已到达流的末尾,则返回 -1.
*/

}

⑩ java实现文件的输入输出的重要性是什么

输入和输出功能是Java对程序处理数据能力的提高,Java以流的形式处理数据。流是一组有序的数据序列,根据操作的类型,分为输入流和输出流。

程序从输入流读取数据,向输出流写入数据。Java是面向对象的程序语言,每一个数据流都是一个对象,它们提供了各种支持“读入”与“写入”操作的流类。

阅读全文

与java的文件输入输出相关的资料

热点内容
android4书籍 浏览:641
pdf阅读器电脑版exe 浏览:907
易语言加壳怎么编译 浏览:523
qt下编译生成mqtt库 浏览:543
南京中兴招收专科程序员吗 浏览:299
代理商php源码 浏览:985
苹果手机怎么解压软件app 浏览:652
游戏资源被编译 浏览:154
代码编译后黑屏 浏览:8
程序员情侣写真 浏览:505
python3孪生素数 浏览:36
计算杨辉三角Python 浏览:404
linux目录重命名 浏览:196
算法设计的最终形态是代码 浏览:262
程序员社团招新横幅 浏览:238
拖鞋解压视频大全 浏览:887
租服务器主机链接软件叫什么 浏览:856
交叉编译工具的linux版本号 浏览:156
python开发应用软件 浏览:32
hdl综合器与c编译器的区别 浏览:899