首页 > 编程语言 >BeginnersBook-Java-IO-教程-一-

BeginnersBook-Java-IO-教程-一-

时间:2024-10-24 18:15:00浏览次数:1  
标签:文件 java file IO import File new Java BeginnersBook

BeginnersBook Java IO 教程(一)

原文:BeginnersBook

协议:CC BY-NC-SA 4.0

如何在 Java 中创建文件

原文: https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/

在本教程中,我们将了解如何使用createNewFile()方法在 Java 中创建文件。如果文件在指定位置不存在并且返回true,则此方法创建一个空文件。如果文件已存在,则此方法返回false。它抛出:

IOException - 如果在创建文件期间发生输入/输出错误。
SecurityException - 如果存在安全管理器且其SecurityManager.checkWrite(java.lang.String)方法拒绝对该文件的写访问。

完整代码:

下面的代码将在 C 盘中创建一个名为newfile.txttxt文件。您可以更改以下代码中的路径,以便在不同目录或不同驱动器中创建文件。

package beginnersbook.com;
import java.io.File;
import java.io.IOException;

public class CreateFileDemo
{
   public static void main( String[] args )
   {	
      try {
	     File file = new File("C:\\newfile.txt");
	     /*If file gets created then the createNewFile() 
	      * method would return true or if the file is 
	      * already present it would return false
	      */
             boolean fvar = file.createNewFile();
	     if (fvar){
	          System.out.println("File has been created successfully");
	     }
	     else{
	          System.out.println("File already present at the specified location");
	     }
    	} catch (IOException e) {
    		System.out.println("Exception Occurred:");
	        e.printStackTrace();
	  }
   }
}

参考:

Javadoc:createNewFile()

如何在 Java 中读取文件 - BufferedInputStream

原文: https://beginnersbook.com/2014/01/how-to-read-file-in-java-bufferedinputstream/

在这个例子中,我们将看到如何使用FileInputStreamBufferedInputStream在 Java 中读取文件。以下是我们在下面的代码中采取的详细步骤:

1)通过在创建文件对象期间提供文件的完整路径(我们将读取)来创建File实例。

2)将文件实例传递给FileInputStream,它打开与实际文件的连接,该文件由文件系统中的File对象文件命名。

3)将FileInputStream实例传递给BufferedInputStream ,它创建BufferedInputStream并保存其参数,即输入流,供以后使用。创建内部缓冲区数组并将其存储在buf中,使用该数组,读取操作可提供良好的性能,因为内容在缓冲区中很容易获得。

4)用于循环读取文件。方法available()用于检查文件的结尾,因为当指针到达文件末尾时返回 0。使用FileInputStreamread()方法读取文件内容。

package beginnersbook.com;
import java.io.*;
public class ReadFileDemo {
   public static void main(String[] args) {         
      //Specify the path of the file here
      File file = new File("C://myfile.txt");
      BufferedInputStream bis = null;
      FileInputStream  fis= null;

      try
      {
          //FileInputStream to read the file
          fis = new FileInputStream(file);

          /*Passed the FileInputStream to BufferedInputStream
           *For Fast read using the buffer array.*/
          bis = new BufferedInputStream(fis);

          /*available() method of BufferedInputStream
           * returns 0 when there are no more bytes
           * present in the file to be read*/
          while( bis.available() > 0 ){             	
              System.out.print((char)bis.read());
          }

       }catch(FileNotFoundException fnfe)
        {
            System.out.println("The specified file not found" + fnfe);
        }
        catch(IOException ioe)
        {
            System.out.println("I/O Exception: " + ioe); 
        }
        finally
        {
            try{
               if(bis != null && fis!=null)
               {
       	          fis.close();
                  bis.close();
               }      
             }catch(IOException ioe)
              {
                  System.out.println("Error in InputStream close(): " + ioe);
              }         
        }
   }    
}

如何在 java 中使用FileOutputStream写入文件

原文: https://beginnersbook.com/2014/01/how-to-write-to-a-file-in-java-using-fileoutputstream/

之前我们看过如何在 Java 中创建一个文件。在本教程中,我们将看到如何使用FileOutputStream在 java 中写入文件。我们将使用FileOutputStreamwrite()方法将内容写入指定的文件。这是write()方法的签名。

public void write(byte[] b) throws IOException

它将指定字节数组中的b.length字节写入此文件输出流。如您所见,此方法需要字节数组才能将它们写入文件。因此,在将内容写入文件之前,我们需要将内容转换为字节数组。

完整代码:写入文件

在下面的例子中,我们将String写入文件。要将String转换为字节数组,我们使用StringgetBytes()方法

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileDemo {
   public static void main(String[] args) {
      FileOutputStream fos = null;
      File file;
      String mycontent = "This is my Data which needs" +
	     " to be written into the file";
      try {
          //Specify the file path here
	  file = new File("C:/myfile.txt");
	  fos = new FileOutputStream(file);

          /* This logic will check whether the file
	   * exists or not. If the file is not found
	   * at the specified location it would create
	   * a new file*/
	  if (!file.exists()) {
	     file.createNewFile();
	  }

	  /*String content cannot be directly written into
	   * a file. It needs to be converted into bytes
	   */
	  byte[] bytesArray = mycontent.getBytes();

	  fos.write(bytesArray);
	  fos.flush();
	  System.out.println("File Written Successfully");
       } 
       catch (IOException ioe) {
	  ioe.printStackTrace();
       } 
       finally {
	  try {
	     if (fos != null) 
	     {
		 fos.close();
	     }
          } 
	  catch (IOException ioe) {
	     System.out.println("Error in closing the Stream");
	  }
       }
   }
}

输出:

File Written Successfully

参考:

FileOutputStream - JavaDoc

使用BufferedWriterPrintWriterFileWriter附加到 java 中的文件

原文: https://beginnersbook.com/2014/01/how-to-append-to-a-file-in-java/

在本教程中,我们将学习如何使用 Java 将内容附加到文件中。有两种方法可以追加:

1)使用FileWriterBufferedWriter:在这种方法中,我们将在一个或多个字符串中包含内容,我们将把这些字符串附加到文件中。该文件可以单独使用FileWriter附加,但使用BufferedWriter可以在维护缓冲区时提高性能。

2)使用PrintWriter:这是将内容附加到文件的最佳方式之一。无论你使用PrintWriter对象写什么都会附加到文件中。

1)使用FileWriterBufferedWriter将内容附加到File

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

class AppendFileDemo
{
   public static void main( String[] args )
   {	
      try{
    	String content = "This is my content which would be appended " +
        	"at the end of the specified file";
        //Specify the file name and path here
    	File file =new File("C://myfile.txt");

    	/* This logic is to create the file if the
    	 * file is not already present
    	 */
    	if(!file.exists()){
    	   file.createNewFile();
    	}

    	//Here true is to append the content to file
    	FileWriter fw = new FileWriter(file,true);
    	//BufferedWriter writer give better performance
    	BufferedWriter bw = new BufferedWriter(fw);
    	bw.write(content);
    	//Closing BufferedWriter Stream
    	bw.close();

	System.out.println("Data successfully appended at the end of file");

      }catch(IOException ioe){
         System.out.println("Exception occurred:");
    	 ioe.printStackTrace();
       }
   }
}

输出:

Data successfully appended at the end of file

让我们说myfile.txt的内容是:

This is the already present content of my file

运行上述程序后,内容将是:

This is the already present content of my fileThis is my content which 
would be appended at the end of the specified file

2)使用PrintWriter将内容附加到File

PrintWriter为您提供更大的灵活性。使用此功能,您可以轻松格式化要附加到File的内容。

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;

class AppendFileDemo2
{
   public static void main( String[] args )
   {	
      try{
          File file =new File("C://myfile.txt");
    	  if(!file.exists()){
    	 	file.createNewFile();
    	  }
    	  FileWriter fw = new FileWriter(file,true);
    	  BufferedWriter bw = new BufferedWriter(fw);
    	  PrintWriter pw = new PrintWriter(bw);
          //This will add a new line to the file content
    	  pw.println("");
          /* Below three statements would add three 
           * mentioned Strings to the file in new lines.
           */
    	  pw.println("This is first line");
    	  pw.println("This is the second line");
    	  pw.println("This is third line");
    	  pw.close();

	  System.out.println("Data successfully appended at the end of file");

       }catch(IOException ioe){
    	   System.out.println("Exception occurred:");
    	   ioe.printStackTrace();
      }
   }
}

输出:

Data successfully appended at the end of file

让我们说myfile.txt的内容是:

This is the already present content of my file

运行上述程序后,内容将是:

This is the already present content of my file
This is first line
This is the second line
This is third line

参考:

如何在 Java 中删除文件 - delete()方法

原文: https://beginnersbook.com/2014/01/how-to-delete-file-in-java-delete-method/

在本教程中,我们将看到如何在 java 中删除文件。我们将使用delete()方法删除文件。

public boolean delete()

如果指定的File成功删除,则此方法返回true,否则返回false

这是完整的代码:

import java.io.File;
public class DeleteFileJavaDemo
{
   public static void main(String[] args)
   {	
      try{
         //Specify the file name and path
    	 File file = new File("C:\\myfile.txt");
         /*the delete() method returns true if the file is
          * deleted successfully else it returns false
          */
    	 if(file.delete()){
    	    System.out.println(file.getName() + " is deleted!");
         }else{
    	    System.out.println("Delete failed: File didn't delete");
    	  }
       }catch(Exception e){
           System.out.println("Exception occurred");
    	   e.printStackTrace();
    	}
    }
}

输出:

myfile.txt is deleted!

参考:

delete() - Javadoc

如何以 GZIP 格式压缩文件

原文: https://beginnersbook.com/2014/07/how-to-compress-a-file-in-gzip-format/

以下代码将指定的文件压缩为 GZip 格式。在下面的示例中,我们在B驱动器的Java文件夹下中有一个文本文件,我们正在压缩并生成同一文件夹中的 GZip 文件。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GZipExample
{
  public static void main( String[] args )
  {
    GZipExample zipObj = new GZipExample();
    zipObj.gzipMyFile();
  }

  public void gzipMyFile(){ 
    byte[] buffer = new byte[1024];
    try{
      //Specify Name and Path of Output GZip file here
      GZIPOutputStream gos = 
       new GZIPOutputStream(new FileOutputStream("B://Java/Myfile.gz"));

      //Specify location of Input file here
      FileInputStream fis = 
       new FileInputStream("B://Java/Myfile.txt");

      //Reading from input file and writing to output GZip file
      int length;
      while ((length = fis.read(buffer)) > 0) {

        /* public void write(byte[] buf, int off, int len): 
         * Writes array of bytes to the compressed output stream.
         * This method will block until all the bytes are written.
         * Parameters:
         * buf - the data to be written
         * off - the start offset of the data
         * len - the length of the data
         */
        gos.write(buffer, 0, length);
      }

      fis.close();

      /* public void finish(): Finishes writing compressed 
       * data to the output stream without closing the 
       * underlying stream.
       */
      gos.finish();
      gos.close();

      System.out.println("File Compressed!!");

    }catch(IOException ioe){
        ioe.printStackTrace(); 
     }
  }
}

输出:

File Compressed!!

参考:

GZIPOutputStream javadoc

如何使用 Java 将文件复制到另一个文件

原文: https://beginnersbook.com/2014/05/how-to-copy-a-file-to-another-file-in-java/

在本教程中,我们将了解如何将一个文件的内容复制到 java 中的另一个文件中。为了复制文件,首先我们可以使用FileInputStream读取文件然后我们可以使用FileOutputStream将读取的内容写入输出文件

下面的代码会将MyInputFile.txt的内容复制到MyOutputFile.txt文件中。如果MyOutputFile.txt不存在,则程序将首先创建文件,然后复制内容。

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

public class CopyExample 
{
    public static void main(String[] args)
    {	
    	FileInputStream instream = null;
	FileOutputStream outstream = null;

    	try{
    	    File infile =new File("C:\\MyInputFile.txt");
    	    File outfile =new File("C:\\MyOutputFile.txt");

    	    instream = new FileInputStream(infile);
    	    outstream = new FileOutputStream(outfile);

    	    byte[] buffer = new byte[1024];

    	    int length;
    	    /*copying the contents from input stream to
    	     * output stream using read and write methods
    	     */
    	    while ((length = instream.read(buffer)) > 0){
    	    	outstream.write(buffer, 0, length);
    	    }

    	    //Closing the input/output file streams
    	    instream.close();
    	    outstream.close();

    	    System.out.println("File copied successfully!!");

    	}catch(IOException ioe){
    		ioe.printStackTrace();
    	 }
    }
}

输出:

File copied successfully!!

上述程序中使用的方法是:

read()方法

public int read(byte[] b) throws IOException

将此输入流中的b.length个字节数据读入一个字节数组。此方法将阻止,直到某些输入可用。它返回读入缓冲区的总字节数,如果没有更多数据,则返回 -1,因为已到达文件末尾。为了使这个方法在我们的程序中工作,我们创建了一个字节数组buffer并将输入文件的内容读取到相同的内容。由于此方法抛出IOException,因此我们将“读取文件”代码放在try-catch块中以处理异常。

write()方法

public void write(byte[] b,
                  int off,
                  int length)
           throws IOException

将从偏移off开始的指定字节数组的长度字节写入此文件输出流。

调整:

如果输入和输出文件不在同一个驱动器中,则可以在创建文件对象时指定驱动器。例如,如果您的输入文件在C盘中并且输出文件在D盘中,那么您可以创建如下文件对象:

File infile =new File("C:\\MyInputFile.txt");
File outfile =new File("D:\\MyOutputFile.txt");

如何在 java 中获取文件的最后修改日期

原文: https://beginnersbook.com/2014/05/how-to-get-the-last-modified-date-of-a-file-in-java/

在这里,我们将学习如何在 java 中获取文件的最后修改日期。为了做到这一点,我们可以使用File类的lastModified()方法。以下是此方法的签名。

public long lastModified()

它返回上次修改此抽象路径名表示的文件的时间。此方法返回的值以毫秒为单位,因此为了使其可读,我们可以使用SimpleDateFormat格式化输出。

完整代码:

这里我们获取文件Myfile.txt的最后修改日期,该日期存在于驱动器C中。由于方法返回的值不可读,我们使用SimpleDateFormat类的format()方法对其进行格式化。

import java.io.File;
import java.text.SimpleDateFormat;
public class LastModifiedDateExample
{
    public static void main(String[] args)
    {	
        //Specify the file path and name
	File file = new File("C:\\Myfile.txt");
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
	System.out.println("Last Modified Date: " + sdf.format(file.lastModified()));
    }
}

输出:

Last Modified Date: 01/03/2014 22:41:49

我们可以以任何所需的格式格式化和显示输出。例如,如果我们使用以下模式:

SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yy HH:mm a");
System.out.println("Last Modified Date: " + sdf2.format(file.lastModified()));

我们将获得以上输出以上模式:

Last Modified Date: 01-03-14 22:41 PM

您可以使用其他几种模式来获得所需形式的输出。要阅读有关日期格式的更多信息,请参阅SimpleDateFormat javadoc

如何在 Java 中创建只读文件

原文: https://beginnersbook.com/2014/05/how-to-make-a-file-read-only-in-java/

在 java 中,使文件只读是非常容易的。在本教程中,我们将学习以下三点。

1)如何使文件只读

2)如何检查现有文件是否处于只读模式

3)如何在 java 中创建可写的只读文件。

1)将文件属性更改为只读

要使文件只读,我们可以使用File类的setReadOnly()方法。它返回一个布尔值,我们可以进一步验证操作是否成功,就像我在下面的程序中一样。正如您在下面的程序中看到的那样,我将文件属性更改为只读取我的计算机“C 盘”中存在的文件Myfile.txt

import java.io.File;
import java.io.IOException;

public class ReadOnlyChangeExample
{

    public static void main(String[] args) throws IOException
    {	
    	File myfile = new File("C://Myfile.txt");
    	//making the file read only
    	boolean flag = myfile.setReadOnly();	
    	if (flag==true)
    	{
    	   System.out.println("File successfully converted to Read only mode!!");
    	}
    	else
    	{
    	   System.out.println("Unsuccessful Operation!!");
    	}
    }
}

输出:

File successfully converted to Read only mode!!

2)检查文件是可写还是只读

为了检查文件属性,我们可以使用文件类的canWrite()方法。如果文件是可写的,则此方法返回true,否则返回false。当我在已经设置为仅在之前的程序中读取的文件Myfile.txt上执行操作时,我将输出为"File is read only"

import java.io.File;
import java.io.IOException;

public class CheckAttributes
{
    public static void main(String[] args) throws IOException
    {	
    	File myfile = new File("C://Myfile.txt");	
    	if (myfile.canWrite())
    	{
    	   System.out.println("File is writable.");
    	}
    	else
    	{
    	   System.out.println("File is read only.");
    	}
    }
}

输出:

File is read only.

3)如何在 java 中创建可写的只读文件

要将只读文件设置为可写文件,我们可以使用setWritable()方法。此方法也可用于使文件只读。
file.setWritable(true):使文件可写。
file.setWritable(false):使文件只读。

import java.io.File;
import java.io.IOException;

public class MakeWritable
{

    public static void main(String[] args) throws IOException
    {	
    	File myfile = new File("C://Myfile.txt");
    	//changing the file mode to writable
    	myfile.setWritable(true);
    	if (myfile.canWrite())
    	{
    	   System.out.println("File is writable.");
    	}
    	else
    	{
    	   System.out.println("File is read only.");
    	}
    }
}

输出:

File is writable.

参考:

File Javadoc

如何在 Java 中检查文件是否隐藏

原文: https://beginnersbook.com/2015/01/how-to-check-if-a-file-is-hidden-in-java/

在本教程中,我们将学习如何编写程序来检查特定文件是否被隐藏。我们将使用File类的isHidden()方法来执行此检查。此方法返回布尔值(truefalse),如果文件被隐藏,则此方法返回true,否则返回false值。

这是完整的代码:

import java.io.File;
import java.io.IOException;

public class HiddenPropertyCheck
{

    public static void main(String[] args) throws IOException, SecurityException
    {	
    	// Provide the complete file path here
    	File file = new File("c:/myfile.txt");

    	if(file.isHidden()){
    		System.out.println("The specified file is hidden");
    	}else{
    		System.out.println("The specified file is not hidden");
    	}
    }
}

关于 javadocisHidden()方法的更多细节:

public static boolean isHidden(Path path) throws IOException

判断文件是否被视为隐藏。隐藏的确切定义是平台或提供者依赖。例如,在 UNIX 上,如果文件的名称以句点字符('.')开头,则认为该文件是隐藏的。在 Windows 上,如果文件不是目录并且设置了 DOS 隐藏属性,则该文件被视为隐藏。
根据实现方式,此方法可能需要访问文件系统以确定文件是否被视为隐藏。

参数:

path - 要测试的文件的路径

返回:

如果文件被视为隐藏,则返回true

抛出:

IOException - 如果发生 I/O 错误

SecurityException - 如果是默认提供程序,并且安装了安全管理器,则调用checkRead方法以检查对文件。

标签:文件,java,file,IO,import,File,new,Java,BeginnersBook
From: https://www.cnblogs.com/apachecn/p/18500088

相关文章

  • BeginnersBook-C-语言示例-一-
    BeginnersBookC语言示例(一)原文:BeginnersBook协议:CCBY-NC-SA4.0C程序:检查阿姆斯特朗数原文:https://beginnersbook.com/2014/06/c-program-to-check-armstrong-number/如果数字的各位的立方和等于数字本身,则将数字称为阿姆斯特朗数。在下面的C程序中,我们检查输入的......
  • BeginnersBook-C---教程-一-
    BeginnersBookC++教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0C++中的for循环原文:https://beginnersbook.com/2017/08/cpp-for-loop/循环用于重复执行语句块,直到满足特定条件。例如,当您显示从1到100的数字时,您可能希望将变量的值设置为1并将其显示100次,在每......
  • HowToDoInJava-Java-教程-二-
    HowToDoInJavaJava教程(二)原文:HowToDoInJava协议:CCBY-NC-SA4.0JVM内存模型/结构和组件原文:https://howtodoinjava.com/java/garbage-collection/jvm-memory-model-structure-and-components/每当执行Java程序时,都会保留一个单独的存储区,用于存储应用程序代码的各......
  • BeginnersBook-Servlet-教程-一-
    BeginnersBookServlet教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0项目的web.xml文件中的welcome-file-list标签原文:https://beginnersbook.com/2014/04/welcome-file-list-in-web-xml/你有没见过web.xml文件中的<welcome-file-list>标签并想知道它是什么?在本文中,我将......
  • BeginnersBook-Perl-教程-一-
    BeginnersBookPerl教程(一)原文:BeginnersBook协议:CCBY-NC-SA4.0Perl-列表和数组原文:https://beginnersbook.com/2017/05/perl-lists-and-arrays/在Perl中,人们可以交替使用术语列表和数组,但是存在差异。列表是数据(标量值的有序集合),数组是保存列表的变量。如何定......
  • StudyTonight-Java-中文教程-六-
    StudyTonightJava中文教程(六)原文:StudyTonight协议:CCBY-NC-SA4.0JavaCharacter.isLetter(char)方法原文:https://www.studytonight.com/java-wrapper-class/java-character-isletterchar-ch-methodJavaisLetter(charch)方法是Character类的一部分。此方法用于检查指......
  • StudyTonight-Java-中文教程-二-
    StudyTonightJava中文教程(二)原文:StudyTonight协议:CCBY-NC-SA4.0JavaFloat类原文:https://www.studytonight.com/java/float-class.phpFloat类将基元类型的浮点值包装在对象中。Float类型的对象包含一个类型为浮点的字段。此外,此类提供了几种将浮点转换为字符串和将......
  • HowToDoInJava-其它教程-2-二-
    HowToDoInJava其它教程2(二)原文:HowToDoInJava协议:CCBY-NC-SA4.0Java核心面试问题–第2部分原文:https://howtodoinjava.com/interview-questions/core-java-interview-questions-series-part-2/在Java面试问题系列:第1部分中,我们讨论了面试官通常问的一些重要......
  • HowToDoInJava-其它教程-1-一-
    HowToDoInJava其它教程1(一)原文:HowToDoInJava协议:CCBY-NC-SA4.0Maven本地仓库位置以及如何更改?原文:https://howtodoinjava.com/maven/change-local-repository-location/在本教程中,学习更改Maven本地仓库的位置。Maven是构建和依赖项管理工具。它将所需的项目......
  • ZetCode-Java-教程-二-
    ZetCodeJava教程(二)原文:ZetCode协议:CCBY-NC-SA4.0Java语法结构原文:http://zetcode.com/lang/java/lexis/像人类语言一样,计算机语言也具有词汇结构。Java程序的源代码由令牌组成。令牌是原子代码元素。在Java中,我们具有注释,标识符,字面值,运算符,分隔符和关键字。Ja......