java 文件流

本文介绍了Java中文件的基本操作,包括控制台打印文件内容、byte数组与字符串的相互转换、从控制台读取字符及字符串的方法。同时,还展示了如何进行文件的读写操作,如创建文件和文件夹,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.控制台打印文件内容

<span style="font-size:14px;"><span style="font-size:14px;">package com.waxberry.pc.pay;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Mydemo {
	
	public static void main(String[] args) {
			         // TODO Auto-generated method stub
			         try {
			         FileInputStream fis=new FileInputStream(new File("E:\\111.txt"));//新建一个FileInputStream对象
			         System.out.println(fis);
			         try {
			              byte[] b=new byte[fis.available()];//新建一个字节数组
			              fis.read(b);//将文件中的内容读取到字节数组中
			              fis.close();
			              String str2=new String(b);//再将字节数组中的内容转化成字符串形式输出
			              System.out.println(str2);
			          } catch (IOException e) {
			              // TODO Auto-generated catch block
			              e.printStackTrace();
			          }
			          
			      } catch (FileNotFoundException e) {
			          // TODO Auto-generated catch block
			          e.printStackTrace();
			      }
			      }
		
		
	}
	
</span></span>

控制台输出:
<span style="font-size:14px;"><span style="font-size:14px;">java.io.FileInputStream@bc8e1e
Hello World!
</span></span>

2.java中如何将byte数组内容转换为字符串?

<span style="font-size:14px;">package com.waxberry.pc.pay;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

public class Mydemo {
	public static void main(String[] args) {
		String str1 = "Hello world!";
		String str2 = "华仔VS邹保健!";
		// string转byte
		byte[] bs1 = str1.getBytes();
		byte[] bs2 = str2.getBytes();
		System.out.println(Arrays.toString(bs1));
		System.out.println(Arrays.toString(bs2));

		// byte转string
		String str11 = new String(bs1);
		String str22 = new String(bs2);
		System.out.println(str11);
		System.out.println(str22);
	}
}</span>

控制台输出:

<span style="font-size:14px;">[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]
[-27, -115, -114, -28, -69, -108, 86, 83, -23, -126, -71, -28, -65, -99, -27, -127, -91, 33]
Hello world!
华仔VS邹保健!</span>

4.从控制台读取多字符输入

// 使用 BufferedReader 在控制台读取字符

import java.io.*;

public class BRRead {
   public static void main(String args[]) throws IOException
   {
      char c;
      // 使用 System.in 创建 BufferedReader 
      BufferedReader br = new BufferedReader(new 
                         InputStreamReader(System.in));
      System.out.println("Enter characters, 'q' to quit.");
      // 读取字符
      do {
         c = (char) br.read();
         System.out.println(c);
      } while(c != 'q');
   }
}

控制台:

Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q


5.从控制台读取字符串

// 使用 BufferedReader 在控制台读取字符
import java.io.*;
public class BRReadLines {
   public static void main(String args[]) throws IOException
   {
      // 使用 System.in 创建 BufferedReader 
      BufferedReader br = new BufferedReader(new
                              InputStreamReader(System.in));
      String str;
      System.out.println("Enter lines of text.");
      System.out.println("Enter 'end' to quit.");
      do {
         str = br.readLine();
         System.out.println(str);
      } while(!str.equals("end"));
   }
}
控制台:

Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end

文件流读写:

<pre name="code" class="java">public String saveBasicImageInfo(FileInputStream is,String userId){
        //获取项目根路径
        String filePath=request.getSession().getServletContext().getRealPath("/imageFile")+"/";
        File file = new File(filePath+userId+".jpg");
        //判断路径是否存在,不存在创建文件
        if(!file.exists())
        {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fos=null; //对应文件建立输出流
        try{
//            is= new FileInputStream(new File(request.getSession().getServletContext().getRealPath("/imageFile")
//                    +"/"+"aa.txt"));
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];//新建缓存  用来存储 从网络读取数据 再写入文件
            int len = 0;
            while((len=is.read(buffer)) != -1){//当没有读到最后的时候
                fos.write(buffer, 0, len);//将缓存中的存储的文件流秀娥问file文件
            }
            fos.flush();//将缓存中的写入file
            fos.close();
            is.close();//将输入流 输出流关闭
        }catch(IOException e){
            e.printStackTrace();
        }
        return filePath;
    }



判断文件是否存在,不存在创建文件:

 File file=new File("C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm");    
    if(!file.exists())    
    {    
        try {    
            file.createNewFile();    
        } catch (IOException e) {    
            // TODO Auto-generated catch block    
            e.printStackTrace();    
        }    
    }    

String path = request.getRealPath("");  
                    File uploadFolder = new File(path + "/upload");  
                    if (!uploadFolder.exists())  
                        uploadFolder.mkdirs();  
                    File file=new File(path + "/upload/" + name);  


判断文件夹是否存在,不存在创建文件夹:

  File file =new File("C:\\Users\\QPING\\Desktop\\JavaScript");    
    //如果文件夹不存在则创建    
    if  (!file .exists()  && !file .isDirectory())      
    {       
        System.out.println("//不存在");  
        file .mkdir();    
    } else   
    {  
        System.out.println("//目录存在");  
    }  

  File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容,一次读一个字节:");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

创建上传目录和上传目录和文件:

import java.io.*;  
public class TestFile {  
      
    public static void main(String[] args) throws Exception {  
        File f = new File("e://xxx//yyy");  
        System.out.println(f.mkdirs());//生成所有目录  
        //f.mkdir();  必须xxx目录存在才能生成yyy目录  
        //f.createNewFile();  
          
        File f2 = new File("E://zzz//t.txt"); //不能生成文件,只能用createNewFile();  
        f2.createNewFile();   //且zzz目录必须存在  
    }  
}  





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值