这里爪子说一下java中的基础:I/O中的一小部分,字符和字节的输入输出:
字符输入输出流(字符方式)
package AllTest;
import java.io.*;
public class CharacterInput_output {
public static void main(String[] args) throws FileNotFoundException {
// 字符输入流示例
Reader reader = new FileReader("class_info.txt");
try{
int data;
while((data = reader.read())!=-1){
char ch = (char)data;
System.out.print(ch);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
// 字符输出流示例
try (Writer writer = new FileWriter("output.txt")) {
String text = "Hello, world!";
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是那个读取的txt文件要放在上一个文件夹里才能在idea中读取,我输入的是“class_info.txt”来作为我的filePath,下面是运行程序的截图:
以上就是字符的输入输出流的操作,相关的操作我已经放在了代码块中。
下面我们看字节输入输出:
字节输入输出流(字节方式)
然后方式都是差不多的,都是FileInputStream一个对象,然后循环读取,然后在来一个FileOutputStream来获取出来当前内容,我把文件名称换为“input.dat”,读出的放在“output.dat”中,大家可以复制过去看一下,放入自己的文件:
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) {
// 字节输入流示例
try (InputStream inputStream = new FileInputStream("input.dat")) {
int data;
while ((data = inputStream.read()) != -1) {
System.out.print(data + " ");
}
} catch (IOException e) {
e.printStackTrace();
}
// 字节输出流示例
try (OutputStream outputStream = new FileOutputStream("output.dat")) {
byte[] data = { 65, 66, 67 }; // A, B, C 的ASCII码
outputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
更多的检查你们自己来看喽!!!
感谢爪子!关注爪子!点赞!收藏!
大学生不容易兄弟们,看看已经“汗流浃背”的牢底吧!
留下你们的作业,本爪子看看怎么个事!!!!!