public class IoTest {
public static void main(String[] args) {
String str = "abcd";
String str1 = "吴危险学java";
System.out.println("字符串转为byte数组:" + Arrays.toString(str.getBytes()));
System.out.println(Arrays.toString(str1.getBytes(StandardCharsets.UTF_8)));
}
}
public class IoTest {
public static void main(String[] args) {
String s="abcd";
//我们要把abcd,装入字节数组中
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
System.out.println(Arrays.toString(bytes));
//将byte字节数组,转成字符串类型
System.out.println(new String(bytes));
}
}
package login;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/*
将字符串转成字节
*/
public class IoTest {
public static void main(String[] args) throws IOException {
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(new FileOutputStream("C:\\Users\\Administrator\\IdeaProjects\\mykt\\write.txt"));
outputStreamWriter.write("已经开始有点晕了");
System.out.println("写入数据成功");
outputStreamWriter.close();
System.out.println("--------------------------");
System.out.println("开始读取数据");
InputStreamReader inputStreamReader = new
InputStreamReader(new FileInputStream("C:\\Users\\Administrator\\IdeaProjects\\mykt\\write.txt"), "utf-8");
char[] charArr = new char[1024];
int len;
while ((len = inputStreamReader.read(charArr)) != -1) {
System.out.println(new String(charArr, 0, len));
}
inputStreamReader.close();
}
}
写入数据总结:
首先new 出fileoutputstream(路径),可不必new出实例对象,直接作为下面的参数
再new outputstreamwriter()再将第一步new的fileoutputstream(路径)
new outputstreamwriter(new的fileoutputstream(路径)),new出实例对象后
.出write()方法,括号内即可写要写入的数据,最后一步,用实例对象,关闭资源
读取数据总结:
首先new 出fileinputstream(路径),可不必new出实例对象,直接作为下面的参数
再new inputstreamreader()再将第一步new的fileinputstream(路径)
new inputstreamreader(new的fileinputstream(路径)) new出实例对象后
用实例对象.出read()方法,该方法若没有读取到数据返回值为-1,可用这个返回值,做循环条件,再创建整形变量,len,来计算数据长度
字节流<字符流
package login;
import java.util.Arrays;
public class Test2 {
public static void main(String[] args) {
char[] chars={'2','2','4','5'};
int[] intArr={1,2,34,5,6,7};
System.out.println(Arrays.toString(chars));
System.out.println(Arrays.toString(intArr));
}
}
package login;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test15 {
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("C:\\Users\\Administrator\\IdeaProjects\\mykt\\test14.txt");
int len;
char[] chars = new char[1024];
while((len= fileReader.read(chars))!=-1){
System.out.println(new String(chars,0,len));
}
fileReader.close();
}
}
package login;
import java.io.*;
public class Test15 {
public static void main(String[] args) throws IOException {
FileWriter fileWriter = new FileWriter("C:\\Users\\Administrator\\IdeaProjects\\mykt\\test15.txt");
fileWriter.write("可恶之前学的,不如后面的这好用");
}
}