天道酬勤,学无止境

File and folder operations-the use of file streams

1. File reading and writing

Idea: The CreateText method of the File class and the WriteLine method of the StreamWriter class are mainly used.

(1) The CreateText method of the File class, which implements the creation or opening of a file for writing UTF-8 encoded text. The syntax is as follows: public static StreamWriter(string path)

(2) WriteLine method of StreamWriter class

This method implements writing a string followed by a line terminator to the file stream. The syntax is as follows:

public virtual void WriteLine(string  value)

Parameter description: value: the string to be written, if value is null, only the end-of-line character is written.

public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)

            {

                textBox1.Text = saveFileDialog1.FileName;

            }

            else

            {

                textBox1.Text = "";

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

if (String.IsNullOrEmpty(textBox1.Text.Trim()))//If the file path is empty

            {

MessageBox.Show("Please set the file path!");

                return;

            }

if (String.IsNullOrEmpty(textBox2.Text.Trim()))//If the text content is empty

            {

MessageBox.Show("Please enter the content of the file!");

                return;

            }

            if (!File.Exists(textBox1.Text))

{//Create or open a file for writing UTF-8 encoded text.

                using (StreamWriter sw = File.CreateText(textBox1.Text))                {

sw.WriteLine(textBox2.Text);//Write the string to the text stream

MessageBox.Show("File created successfully", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

            }

            else

            {

MessageBox.Show("The file already exists", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

        }

    }

2. The OpenRead method opens an existing file and reads it

Idea: The OpenRead method of the File class and the Read method of the FileStream class are mainly used.

(1) The OpenRead method of the File class, which implements opening an existing file for reading. The syntax format is as follows:

public static FileStream OpenRead(string path)

Parameter description: path: the file to be opened for reading.

Return value: The read-only file stream on the specified path.

(2) Read method of FileStream class

This method realizes fast reading bytes from the stream and writing the data into the given buffer. The syntax is as follows:

public override int Read(byte[] array,int offset,int count)

Description of the parameters in the Read method:

parameter

Description

Array

Buffer for writing data

Offset

Start index of reading

Count

Maximum number of bytes read

return value

The total number of bytes read into the Buffer. If the current number of bytes is not as many as requested, the total number of bytes may be less than the requested number of bytes; or if the end of the stream has been reached, it is zero.

Example:

private void button1_Click(object sender, EventArgs e)

        {

            try

            {

openFileDialog1.Filter = "Text file(*.txt)|*.txt";//Set the type of open file

                openFileDialog1.ShowDialog();

textBox1.Text = openFileDialog1.FileName;//Set the name of the opened file

FileStream fs = File.OpenRead(textBox1.Text);//Open an existing file for reading

byte[] b = new byte[1024];//define buffer

while (fs.Read(b, 0, b.Length)> 0)//The loop reads 1024 bytes each time into the cache

{//Turn all the bytes of the byte array into a string

                    textBox2.Text = Encoding.Default.GetString(b);              

 }

            }

catch {MessageBox.Show("Please select a file");}

        }

3. Use the OpenWrite method to open an existing file and write

Idea: To use the OpenWrite method of the File class, the GetBytes method of the Encoding abstract class and the Write method of the FileStream class.

  1. OpenWrite method of File class

This method is used to open an existing file for writing. The syntax is as follows:

Public static FileStream OpenWrite(string path)

Parameter description: path: the file to be opened for writing.

Return value: Return the fly shared file stream object on the specified path with write permission.

  1. The GetBytes method of the Encoding abstract class. This method is used to encode all characters in the specified string into a byte sequence. The syntax is as follows: public virtual byte[] GetBytes(string s)

Parameter description: s: a string containing the characters to be encoded.

Return value: Return a byte array containing the result of encoding the specified character set.

  1. The Write method of the FileStream class. This method implements the use of data read from the buffer to write byte blocks to the stream. The syntax is as follows: public override void Write(byte[] array,int offset,int count)

Description of the parameters in the Write method:

parameter

Description

Array

The buffer containing the data to be written to the stream

Offset

The position index from which to copy bytes to the current stream

Count

The maximum number of bytes to be written to the current stream.

return value

No return value

Example:

  public partial class Form1 : Form {

public Form1()

{  InitializeComponent();}

        private void button1_Click(object sender, EventArgs e)

        {

openFileDialog1.Filter = "Text file (*.txt)|*.txt";

            openFileDialog1.ShowDialog();

            textBox1.Text = openFileDialog1.FileName;

        }

        private void button2_Click(object sender, EventArgs e)

        {

          

            if (String.IsNullOrEmpty(textBox1.Text.Trim()))

            {

MessageBox.Show("Please set up the file!");

                return;

            }

            try

            {

                FileStream FStream = File.OpenWrite(textBox1.Text);

                Byte[] info = Encoding.Default.GetBytes(textBox2.Text);

                FStream.Write(info, 0, info.Length);

                FStream.Close();

MessageBox.Show("File successfully written!");

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

}

3. Open the existing UTF-8 encoded text file and read it

Idea: Mainly use the OpenText method of the File class and the ReadToEnd method of the StreamReader class,

  1. The OpenText method of the File class, which implements opening an existing UTF-8 encoded text file for reading. The syntax is as follows: public static StreamReader OpenText(string path)

(2) ReadToEnd() of the StreamReader class. Parameter description: Return value: Return the rest of the stream in string form (from the current position to the end). If the current position is at the end of the stream, an empty string ("") is returned.

Example:

private void button1_Click(object sender, EventArgs e)

        {

            try

            {

openFileDialog1.Filter = "Text file (*.txt)|*.txt";

                openFileDialog1.ShowDialog();

                textBox1.Text = openFileDialog1.FileName;

                StreamReader SReader = File.OpenText(textBox1.Text);

                textBox2.Text = SReader.ReadToEnd();

            }

            catch { }

        }

4. Read the first row of data in the file

The main method used: ReadLine();

openFileDialog1.Filter = "Text file (*.txt)|*.txt";

                openFileDialog1.ShowDialog();

                textBox1.Text = openFileDialog1.FileName;

                StreamReader SReader = new StreamReader(textBox1.Text, Encoding.Default);

                textBox2.Text = SReader.ReadLine();

5. Convert text files into web files

Idea: Mainly use the AppendText method and SaveFile method of the RichTextBox control.

(1) AppendText method of the RichTextBox control, which implements appending text to the current text of the text box, the format is as follows:

Public void AppendText(string text)

  1. SaveFile method, which implements to save the contents of RichTextBox to a file of a specific class Cininggong, the syntax is as follows: public void Save File(string path,RichTextBoxStreamType fileType)

FileType: one of the RichTextBoxStreamType enumeration,

Enumerated value

Description

RichText

RTF format stream

PlainText

Replace the plain text flow of object connection and embedding (OLE) objects with spaces

RichNoOleObjs

Rich text format (RTF format) stream with spaces instead of OLE objects

TextTextOleObjs

Plain text stream with text representation of OLE objects

UnicodePlainText

Text stream containing spaces instead of object linking and embedding (OLE) objects

 

Example:

string strContent = "##Technology Co., Ltd. is a high-tech enterprise with computer software technology as its core. For many years, it has been committed to the development of industry management software, the production of digital publications, the comprehensive application of computer network systems, and the development of industry e-commerce websites. Involving production, management, control, warehousing, logistics, marketing, services and other industries. The company has senior experts in software development and project implementation and a learning technical team. Over the years, it has accumulated a wealth of technical documents and learning materials. The company’s development team Not only is a pioneering technology practitioner, but also committed to becoming a popularization and disseminator of technology.";

string strCompany = "##科技有限公司";

                string strWeb = "www.##soft.com";

string strFileName = "Company website.htm";

                richTextBox1.Clear();

                richTextBox1.AppendText("

                richTextBox1.AppendText("

                richTextBox1.AppendText("

                richTextBox1.AppendText(strCompany);

                richTextBox1.AppendText("");

                richTextBox1.AppendText("");

                richTextBox1.AppendText("

                richTextBox1.AppendText("

");

                richTextBox1.AppendText("

" + strCompany + "

");

                String strHyper = "

Welcome to the website of **Technology Company:";

                richTextBox1.AppendText(strHyper + strWeb + "");

                richTextBox1.AppendText("");

                richTextBox1.AppendText(strContent);

                richTextBox1.AppendText("");

                richTextBox1.AppendText("");

                richTextBox1.SaveFile(strFileName, RichTextBoxStreamType.PlainText);

                System.Diagnostics.Process.Start(strFileName);

6. Read and write memory stream data

Mainly use the Capacity property, Write method and Read method of the MemoryStream class.

Example:

private void button1_Click(object sender, EventArgs e)

        {

            byte[] BContent = Encoding.Default.GetBytes(textBox1.Text);

            MemoryStream MStream = new MemoryStream(100);

            MStream.Write(BContent, 0, BContent.Length);

richTextBox1.Text = "The number of bytes allocated to the stream:" + MStream.Capacity.ToString() + "\nStream length:"

+ MStream.Length.ToString() + "\nThe current position of the stream:" + MStream.Position.ToString();

            MStream.Seek(0, SeekOrigin.Begin);

            byte[] byteArray = new byte[MStream.Length];

            int count = MStream.Read(byteArray, 0, (int)MStream.Length - 1);

            while (count < MStream.Length)

            {

                byteArray[count++] = Convert.ToByte(MStream.ReadByte());

            }

            char[] charArray = new char[Encoding.Default.GetCharCount(byteArray, 0, count)];

            Encoding.Default.GetChars(byteArray, 0, count, charArray, 0);

            for (int i = 0; i < charArray.Length; i++)

            {

                richTextBox2.Text += charArray[i].ToString();

            }

        }

6. Create and write binary file data

Idea: Mainly use the construction method and Write method of the BinaryWriter class.

例: private void button2_Click(object sender, EventArgs e)

 {

  if (String.IsNullOrEmpty(textBox1.Text.Trim()))

            {

MessageBox.Show("Please select the file path");

                return;

            }

            if (String.IsNullOrEmpty(textBox2.Text.Trim()))

            {

MessageBox.Show("Please set the file name");

                return;

            }

            try

            {

                FileStream myStream = new FileStream(textBox1.Text + "\\" + textBox2.Text+".bin", FileMode.Create);

                BinaryWriter myWriter = new BinaryWriter(myStream);

                for (int i = 0; i < 10; i++)

                {

                    myWriter.Write(i);

                }

                myWriter.Close();

                myStream.Close();

MessageBox.Show("Created and written successfully!");

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

7. Read the contents of the binary file

Example:

  private void button1_Click(object sender, EventArgs e)

        {

            openFileDialog1.Filter = "*.bin|*.bin";

            openFileDialog1.ShowDialog();

            textBox1.Text = openFileDialog1.FileName;

        }

        private void button2_Click(object sender, EventArgs e)

        {

            if (String.IsNullOrEmpty(textBox1.Text.Trim()))

            {

MessageBox.Show("Please select a file");

                return;

            }

            textBox2.Text = string.Empty;

            try

            {

                FileStream myStream = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);

                BinaryReader myReader = new BinaryReader(myStream);

                for (int i = 0; i < myStream.Length; i++)

                {

                    textBox2.Text += myReader.ReadInt32();

                }

                myReader.Close();

                myStream.Close();

            }

            catch { }

        }

8. Use a buffered stream to copy files

Idea: When using a buffered stream, you need to use the BufferedStream class under the System.IO namespace. The BufferedStream stream is also called a buffered stream. It implements adding a buffer layer to read and write operations on another stream. The buffer stream creates a buffer in memory. It reads bytes from the disk to the buffer in the most efficient increment, and it reads the bytes from the disk to the buffer in the most efficient increment. The buffer is a block of bytes in memory that is used to cache data to reduce the number of calls to the operating system. The buffer can improve read and write performance.

  1. The Read method of the BufferedStream class. This method implements copying the bytes from the current buffer stream to the array. The format is as follows: public override int Read(byte[] array,int offset,int count)

parameter

Description

Array

Copy bytes to buffer

Offset

Position index from which to start reading bytes

Count

The number of bytes to read

return value

The total number of bytes read into the array byte array. If there are not as many bytes as requested, the total number of bytes may be less than the number of bytes requested; or if the end of the stream is reached before any data can be read, it is zero.

  1. The Write method of the BufferedStream class. This method realizes copying bytes to the buffer stream, and advances the current position in the buffer stream by the number of bytes written. The syntax is as follows: public override void Write(byte[] array, int offset, int count). Write parameter description:

parameter

Description

Array

Byte array, from which count bytes are copied to the current buffer stream.

Offset

The offset of the buffer from which to copy bytes to the current buffer stream

Count

The number of bytes to be written to the current buffer stream

return value

No return value

  1. The Flush method of the BufferedStream class. This method realizes clear all buffers of the stream, so that all buffered data is written to the basic device. Syntax format: public override void Flush()

Note: Because the buffer stream reads and writes data directly in the buffer of the memory, instead of directly reading and writing data from the hard disk, it is particularly suitable for processing large-capacity files.

Example:

   public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

openFileDialog1.Filter = "File(*.*)|*.*";

            openFileDialog1.ShowDialog();

            textBox1.Text = openFileDialog1.FileName;

        }

        private void button2_Click(object sender, EventArgs e)

        {

            folderBrowserDialog1.ShowDialog();

            textBox2.Text = folderBrowserDialog1.SelectedPath;

        }

        private void button3_Click(object sender, EventArgs e)

        {

            try

            {

                string str1 = textBox1.Text;

                string str2 = textBox2.Text + "\\" + textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1, textBox1.Text.Length - textBox1.Text.LastIndexOf("\\") - 1);

                Stream myStream1, myStream2;

                BufferedStream myBStream1, myBStream2;

                byte[] myByte = new byte[1024];

                int i;

                myStream1 = File.OpenRead(str1);

                myStream2 = File.OpenWrite(str2);

                myBStream1 = new BufferedStream(myStream1);

                myBStream2 = new BufferedStream(myStream2);

                i = myBStream1.Read(myByte, 0, 1024);

                while (i > 0)

                {

                    myBStream2.Write(myByte, 0, i);

                    i = myBStream1.Read(myByte, 0, 1024);

                }

                myBStream2.Flush();

                myStream1.Close();

                myBStream2.Close();

MessageBox.Show("File copy completed");

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

}

9. How to use GzipStream to compress files?

The GzipStream class is located in the System.IO.Compression namespace and provides methods and properties for compressing and decompressing streams. This category represents the GZip data format, which includes a cyclic redundancy check value to detect data corruption. After constructing a compressed stream using the GzipStream class, you can use the Write method of this class to write data to achieve compression.

  1. The Write method implements writing the bytes to be compressed into the basic stream from the specified byte array. The syntax is as follows:

Public override void Write(byte[] array,int offset, int count)

Parameter description: (1) array is used to store the array of bytes to be compressed. (2) Start reading position in the offset array (2) count The number of compressed bytes.

using System.IO.Compression;

namespace GZipFile

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

openFileDialog1.Filter = "All files(*.*)|*.*";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)

            {

                textBox1.Text = openFileDialog1.FileName;

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            if (String.IsNullOrEmpty(textBox1.Text))

            {

MessageBox.Show("Please select the source file!", "Information Prompt");

                return;

            }

            if (String.IsNullOrEmpty(textBox2.Text))

            {

MessageBox.Show("Please enter the compressed file name!", "Information Prompt");

                return;

            }

            string str1 = textBox1.Text;

            string str2 = textBox2.Text.Trim();

            byte[] myByte = null;

            FileStream myStream = null;

            FileStream myDesStream = null;

            GZipStream myComStream = null;

            try

            {

                myStream = new FileStream(str1, FileMode.Open, FileAccess.Read, FileShare.Read);

                myByte = new byte[myStream.Length];

                myStream.Read(myByte, 0, myByte.Length);

                myDesStream = new FileStream(str2, FileMode.OpenOrCreate, FileAccess.Write);

                myComStream = new GZipStream(myDesStream, CompressionMode.Compress, true);

                myComStream.Write(myByte, 0, myByte.Length);

MessageBox.Show("The compressed file is complete!");

            }

            catch { }

            finally

            {

                myStream.Close();

                myComStream.Close();

                myDesStream.Close();

            }

        }

    }

}

10. How to use Gzip to decompress files

Idea: Use the Read method of the GzipStream class to read data to achieve decompression. The syntax is as follows:

Public override int Read(byte[] array,int offset,int count)。

Parameter description: (1) array is an array used to store compressed bytes. (2) Start reading position in the offset array (3) count The number of bytes decompressed. (4) The returned value is the number of bytes decompressed into the byte array.If the end of the stream has been reached, return 0 or the number of bytes read

using System.IO.Compression;

namespace UnGzipFile

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

openFileDialog1.Filter = "Compressed file(*.gzip)|*.gzip";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)

            {

                textBox1.Text = openFileDialog1.FileName;

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            if (String.IsNullOrEmpty(textBox1.Text))

            {

MessageBox.Show("Please select the GZIP file!", "Message Prompt");

                return;

            }

            if (String.IsNullOrEmpty(textBox2.Text))

            {

MessageBox.Show("Please enter the decompressed file name!", "Information Prompt");

                return;

            }

            string str1 = textBox1.Text;

            string str2 = textBox2.Text.Trim();

            byte[] myByte = null;

            FileStream myStream = null;

            FileStream myDesStream = null;

            GZipStream myDeComStream = null;

            try

            {

                myStream = new FileStream(str1, FileMode.Open);

                myDeComStream = new GZipStream(myStream, CompressionMode.Decompress, true);

                myByte = new byte[4];

                int myPosition = (int)myStream.Length - 4;

                myStream.Position = myPosition;

                myStream.Read(myByte, 0, 4);

                myStream.Position = 0;

                int myLength = BitConverter.ToInt32(myByte, 0);

                byte[] myData = new byte[myLength + 100];

                int myOffset = 0;

                int myTotal = 0;

                while (true)

                {

                    int myBytesRead = myDeComStream.Read(myData, myOffset, 100);

                    if (myBytesRead == 0)

                        break;

                    myOffset += myBytesRead;

                    myTotal += myBytesRead;

                }

                myDesStream = new FileStream(str2, FileMode.Create);

                myDesStream.Write(myData, 0, myTotal);

                myDesStream.Flush();

MessageBox.Show("Extracting the file is complete!");

            }

            catch { }

            finally

            {

                myStream.Close();

                myDeComStream.Close();

                myDesStream.Close();

            }

        }

    }

}

11. Call WinRAR to realize file compression and decompression

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Web; 

using System.Web.UI; 

using System.Web.UI.WebControls; 

using System.Diagnostics; 

using System.IO; 

public partial class Zip : System.Web.UI.Page 

    protected void Page_Load(object sender, EventArgs e) 

    { 

    } 

//Compressed file

    protected void Button1_Click(object sender, EventArgs e) 

    { 

        ProcessStartInfo startinfo = new ProcessStartInfo(); ; 

        Process process = new Process(); 

string rarName = "1.rar"; //File name after compression

string path = @"C:\images"; //To be compressed and packaged folder

string rarPath = @"C:\zip"; //Save the folder after compression

string rarexe = @"c:\Program Files\WinRAR\WinRAR.exe"; //WinRAR installation location

        try 

        { 

//Compression command, equivalent to right-click on the folder (path) to be compressed -> WinRAR -> add to compressed file -> enter the compressed file name (rarName)

            string cmd = string.Format("a {0} {1} -r", 

                                rarName, 

                                path); 

            startinfo.FileName = rarexe; 

startinfo.Arguments = cmd; //Set command parameters

startinfo.WindowStyle = ProcessWindowStyle.Hidden; //Hide the WinRAR window

            startinfo.WorkingDirectory = rarPath; 

            process.StartInfo = startinfo; 

            process.Start(); 

process.WaitForExit(); //Wait indefinitely for the process winrar.exe to exit

            if (process.HasExited) 

            { 

MSCL.JsHelper.Alert("Compression succeeded!", Page);

            } 

        } 

        catch (Exception ex) 

        { 

            MSCL.JsHelper.Alert(ex.Message, Page); 

        } 

        finally 

        { 

            process.Dispose(); 

            process.Close(); 

        }         

    } 

//unzip files

    protected void Button2_Click(object sender, EventArgs e) 

    { 

        ProcessStartInfo startinfo = new ProcessStartInfo(); ; 

        Process process = new Process(); 

string rarName = "1.rar"; //The name of the .rar file to be decompressed (including the suffix)

string path = @"C:\images1"; //File decompression path (absolute)

string rarPath = @"C:\zip"; //The storage directory of the .rar file to be decompressed (absolute path)

string rarexe = @"c:\Program Files\WinRAR\WinRAR.exe"; //WinRAR installation location

        try 

        { 

//Unzip command, equivalent to right click on the file (rarName) to be compressed ->WinRAR->extract to the current folder

            string cmd = string.Format("x {0} {1} -y", 

                                rarName, 

                                path); 

            startinfo.FileName = rarexe; 

startinfo.Arguments = cmd; //Set command parameters

startinfo.WindowStyle = ProcessWindowStyle.Hidden; //Hide the WinRAR window

            startinfo.WorkingDirectory = rarPath; 

            process.StartInfo = startinfo; 

            process.Start(); 

process.WaitForExit(); //Wait indefinitely for the process winrar.exe to exit

            if (process.HasExited) 

            { 

MSCL.JsHelper.Alert("Unzipped successfully!", Page);

            } 

        } 

        catch (Exception ex) 

        { 

            MSCL.JsHelper.Alert(ex.Message, Page); 

        } 

        finally 

        { 

            process.Dispose(); 

            process.Close(); 

        }    

    } 

}

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • Byte stream, character stream (IO stream, byte stream, character stream, exception handling, Properties)
    1. IO stream <br /> Definition: The transmission of data is regarded as the flow of data. According to the method of flow, it is divided into input stream and output stream. IO stream operation refers to the use of the contents of the java.io package for input and output. Input is called read, output is called write out data classification: Input stream and output stream (according to the direction of data flow) Input stream: read data from the hard disk to the memory output stream: write data from the memory to the hard disk byte stream and character stream (data according to format)Byte
  • Reading embedded XML file c#
    Question How can I read from an embedded XML file - an XML file that is part of a c# project? I've added a XML file to my project and I want to read from it. I want the XML file to compile with the project because I don't want that it will be a resource which the user can see. Any idea? Answer1 Make sure the XML file is part of your .csproj project. (If you can see it in the solution explorer, you're good.) Set the "Build Action" property for the XML file to "Embedded Resource". Use the following code to retrieve the file contents at runtime: public string GetResourceTextFile(string filename)
  • Iterating over directories with Gulp?
    Question I'm new to gulp, but I'm wondering if its possible to iterate through directories in a gulp task. Here's what I mean, I know a lot of the tutorials / demos show processing a bunch of JavaScript files using something like "**/*.js" and then they compile it into a single JavaScript file. But I want to iterate over a set of directories, and compile each directory into it's own JS file. For instance, I have a file structure like: /js/feature1/something.js /js/feature1/else.js /js/feature1/foo/bar.js /js/feature1/foo/bar2.js /js/feature2/another-thing.js /js/feature2/yet-again.js ...And I
  • 6. Java study notes: File class, recursion; IO stream, byte stream, character stream, IO exception handling, attribute set, properties class; buffer stream, conversion stream, serialization stream, print stream
    parter1 File class recursion 1 File class 1.1File class java.io.File //类式文件和目录路径名的抽象表示,主要用于文件和目录的创建,查找和删除等操作。 Java encapsulates the files and folders in the computer into a File class, and we can use the File class to manipulate files and folders.Create/delete/judgment/get/traverse files/folders The File class has nothing to do with the system, and any operating system can use the methods of this class. Three key words: File: file directory: folder/directory path: path.变量: pathSeparator :路径分隔符,WIndows 是; Linux 是: pathSeparatorChar : separator :默认名称分隔符/文件分割符windows 是\ Linux 是/ separatorChar
  • Copy directory from Assets to local directory
    Question I'm trying to use a directory that I have in my assets folder and access it as a File. Is it possible to access something in the Assets directory as a File? If not, how can I copy a directory from the Assets folder to the application's local directory? I would copy a file like so: try { InputStream stream = this.getAssets().open("myFile"); OutputStream output = new BufferedOutputStream(new FileOutputStream(this.getFilesDir() + "/myNewFile")); byte data[] = new byte[1024]; int count; while((count = stream.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close
  • [C++ files and streams] simple text file read and write operations
    Simple file read and write operationsClass and reference description fstream iostreamRead and write operations: write to and read from text Class and reference description Two classes of fstream and iostream need to be referenced. After vs2012 is opened, the header file stdafx.h is automatically imported. #include "stdafx.h" #include <iostream> #include <fstream> As a carrier, the stream can be directly exchanged with the file. Therefore, after the stream is opened, the read and write of the stream (implemented with stream output <<, stream input >>) is the read and write operation of the file
  • One of the series of lectures on Citrix Profile Management and VDI: How to properly manage Profile
    I met a customer yesterday, and he asked us to help him plan the size of the back-end Profile , how much space each person, what storage type to choose, and even complained about the troublesome management. Feeling this, I have synthesized various materials and prepared to write a series of articles about Profile , which will be released in three phases. Today is the first phase. Let’s talk about the difficulties of Profile configuration. Previously stated, the following is not about what the answer is Profile of popular science articles about what Profile, or what is the Folder redirector use
  • C# study notes [fourteen]-file operation
    14.1 File read and write method The following classes are used to browse the file system and perform operations, such as moving, copying, and deleting files System.MarshalByRefObject This is the base object class for remote operations in the .NET class, which allows data to be grouped between application domains. classeffect FileSystemInfoThis is the base class that represents any file system object FileInfo and FileThese classes represent files on the file system DirectoryInfo and DirectoryRepresents a folder on the file system PathContains some static methods for processing path names
  • Practical application of file streaming
    About file flow: File byte input stream: FileInputStream class The file byte input stream can read byte data from the file of the specified path. The file byte input stream inherits the InputStream class and implements various methods of reading the input stream. The construction method of creating a file byte input stream: 1. Create a FileInputStream with the File object as a parameter new FileInputStream(File file) Create a FileInputStream instance with the absolute path of the file object as a parameter new FileInputStream(String filePath) File byte output stream: FileOutPutSteam The file
  • File class overview, construction method, absolute path and relative path; File class creation, deletion, judgment and acquisition functions; byte stream: IO stream overview and classification, byte stream write data three ways, two minor problems and exc
    1.File class 1.1File class overview and construction method (application) File class introduction It is an abstract representation of file and directory pathsFiles and directories can be encapsulated into objects by FileFor File, what it encapsulates is not a real file, just a path name. It can exist or not. In the future, the content of this path will be converted to Concrete The construction method of the File class Sample code public class FileDemo01 { public static void main(String[] args) { //File(String pathname): 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例 File f1 = new File("E:\\itcast\\java.txt"
  • Creating Directories in a ZipArchive C# .Net 4.5
    Question A ZipArchive is a collection of ZipArchiveEntries, and adding/removing "Entries" works nicely. But it appears there is no notion of directories / nested "Archives". In theory, the class is decoupled from a file system, in that you can create the archive completely in a memory stream. But if you wish to add a directory structure within the archive, you must prefix the entry name with a path. Question: How would you go about extending ZipArchive to create a better interface for creating and managing directories? For example, the current method of adding a file to a directory is to
  • Read file from resources folder in Spring Boot
    Question I'm using Spring Boot and json-schema-validator. I'm trying to read a file called jsonschema.json from the resources folder. I've tried a few different ways but I can't get it to work. This is my code. ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("jsonschema.json").getFile()); JsonNode mySchema = JsonLoader.fromFile(file); This is the location of the file. And here I can see the file in the classes folder. But when I run the code I get the following error. jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev
  • Unzip a memorystream (Contains the zip file) and get the files
    Question I have a memory stream that contains a zip file in byte[] format . Is there any way I can unzip this memory stream, without any need of writing the file to disk ? In general I am using ICSharpCode.SharpZipLib.Zip.FastZip to unzip a file , But any way to unzip a memory stream ? and store the files in another memorystream or in byte[] format according to the files/folders present in the zip ? Any way I can use the Memorymapped files feature in this scenario ? Answer1 We use DotNetZip, and I can unzip the contents of a zip file from a Stream into memory. Here's the sample code for
  • how to read a text file in windows universal app
    Question I am trying to read a text file named thedata.txt that has a list of words that I want to use in a hangman game. I have tried different ways, but I can't figure out where the file gets placed, if at all when the app runs. I added the file to my project, and I have tried setting the build properties to content, and then embedded resource, but can't find the file. I have made a Windows 10 universal app project. The code I tried looks like this: Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("thedata.txt"); using (StreamReader inputStream = new
  • Need to convert text files to Unicode from UTF8 in vbscript
    Question I have a bunch of text files in a folder that I need to change the encoding on to Unicode and instead of manually opening the files and saving them as Unicode I would like to have a script to do this. The files are currently in UTF-8 encoding and my extremely limited scripting abilities can't figure this one out. I found the code below to convert to Unicode from ANSI and when I use this code it does convert it to Unicode but it messes up the characters so the conversion doesn't actually work. Any thoughts? Thanks in advance. Set fso = CreateObject("Scripting.FileSystemObject") Set
  • file_put_contents(meta/services.json): failed to open stream: Permission denied
    Question I am new to Laravel. I was trying to open http://localhost/test/public/ and I got Error in exception handler. I googled around and changed the permission of storage directory using chmod -R 777 app/storage but to no avail. I changed debug=>true in app.php and visited the page and got Error in exception handler: The stream or file "/var/www/html/test/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/html/test/bootstrap/compiled.php:8423 Then I changed the permissions of storage directory using the command chmod -R 644 app/storage
  • How to check if a folder exists
    Question I am playing a bit with the new Java 7 IO features, actually I trying to receive all the xml files of a folder. But this throws an exception when the folder does not exist, how can I check if the folder exists with the new IO? public UpdateHandler(String release) { log.info("searching for configuration files in folder " + release); Path releaseFolder = Paths.get(release); try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){ for (Path entry: stream){ log.info("working on file " + entry.getFileName()); } } catch (IOException e){ log.error("error while
  • A Generic error occurred in GDI+ in Bitmap.Save method
    Question I am working on to upload and save a thumbnail copy of that image in a thumbnail folder. I am using following link: http://weblogs.asp.net/markmcdonnell/archive/2008/03/09/resize-image-before-uploading-to-server.aspx but newBMP.Save(directory + "tn_" + filename); is causing exception "A generic error occurred in GDI+." I have tried to give permission on folder, also tried to use a new separate bmp object when saving. Edit: protected void ResizeAndSave(PropBannerImage objPropBannerImage) { // Create a bitmap of the content of the fileUpload control in memory Bitmap originalBMP = new
  • java io to create a folder _JavaIO stream-create file and folder program example
    Tag: *Create function: *public boolean createNewFile(): Create a file. If such a file exists, it will not be created (calling file.createNewFile() will return false) *public boolean mkdir(): Create a folder. If such a folder exists, it will not be created (calling file.mkdir() will return false) *public boolean mkdirs(): create a folder, if the parent folder does not exist, it will be created for you (call file.mkdirs() will return false) * *It is not necessarily the prince who rides the white horse, but the squad leader. a.txt is not necessarily a file, it may be a folder *Note: Whether you
  • move_uploaded_file() failed to open stream: no such file or directory
    Question I've done your standard checks (is the directory there, are lax enough permissions set), and I'm pretty sure I've covered your standard stupid human tricks. Here's the code that's failing: move_uploaded_file($_FILES['image1']['tmp_name'], "/public_html/flashsale/assets/img/products/T".$_FILES['image1']['name']); The directory is there - I copied the path from FileZilla. I even set the permissions to 777, both in FileZilla and in the file manager on the HostGator control panel. This code generates two warnings: Message: move_uploaded_file(/public_html/flashsale/assets/img/products