public class TestWrite
{
public static void main(String[] args)
{// 注意: Win10下面不允许直接在根分区下创建文件,如C:/sample.txt是不行的// 必须先创建一个子目录,然后在子目录下创建测试文件// 创建一个临时目录File dir = new File("E:\\linkdata\\Java_Example");dir.mkdirs();// 文件路径 File file = new File(dir, "sample");// 数据byte[] data = { 1, 2, 3, 4};try {FileOutputStream outputStream = new FileOutputStream( file );outputStream.write(data,0,4);// 写入4个字节outputStream.close();}catch(Exception e){e.printStackTrace();}System.out.println("Exit");}
}
public class TestRead
{public static void main(String[] args){// 创建一个临时目录File dir = new File("E:\\linkdata\\Java_Example");dir.mkdirs();// 文件路径File file = new File(dir, "sample");// 因为不知道文件有多大,所以准备一个大些的数组byte[] data = new byte[1000];try{FileInputStream inputStream = new FileInputStream(file);int n = inputStream.read(data);// 返回值n表示实际读取的字节数inputStream.close();System.out.println("读出 " + n + " 字节");} catch (Exception e){e.printStackTrace();}System.out.println("Exit");}}
public class TestWrite
{public static void main(String[] args){// 注意: Win10下面不允许直接在根分区下创建文件,如C:/sample.txt是不行的// 必须先创建一个子目录,然后在子目录下创建测试文件// 创建一个临时目录File dir = new File("E:\\linkdata\\Java_Example");dir.mkdirs();// 文件路径 File file = new File(dir, "abc.txt");// 文本String text = "Hi,大家好,我是邵发!";try {// 将文本编码为数据, 按 GBK 或 UTF-8 编码byte[] data = text.getBytes("GBK");FileOutputStream outputStream = new FileOutputStream( file );outputStream.write(data);outputStream.close();System.out.println("写入: " + file.getAbsolutePath());}catch(Exception e){e.printStackTrace();}System.out.println("Exit");}}
public class TestRead
{public static void main(String[] args){// 创建一个临时目录File dir = new File("E:\\linkdata\\Java_Example");dir.mkdirs();// 文件路径File file = new File(dir, "abc.txt");// 因为不知道文件有多大,所以准备一个大些的数组byte[] data = new byte[1000];try{System.out.println("读取: " + file.getAbsolutePath());FileInputStream inputStream = new FileInputStream(file);int n = inputStream.read(data);// 返回值n表示实际读取的字节数inputStream.close();String text = new String(data, 0, n, "GBK");System.out.println("读出 " + n + " 字节:");System.out.println(text);} catch (Exception e){e.printStackTrace();}System.out.println("Exit");}}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态