search
HomeJavajavaTutorialHow to convert strings and input streams in Java

Mutual conversion between strings and input streams

When reading network resources, the mutual conversion between strings and input streams is often used. I found some methods and recorded them.

Convert the string into an input stream, the code is as follows:

public static InputStream getStringStream(String sInputString){ 
  if (sInputString != null && !sInputString.trim().equals("")){ 
      try{ 
          ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes()); 
          return tInputStringStream; 
      }catch (Exception ex){ 
          ex.printStackTrace(); 
      } 
  } 
  return null; 
}

Convert the input stream into a string, the code is as follows:

public static String getStreamString(InputStream tInputStream){ 
  if (tInputStream != null){ 
       try{ 
            BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(tInputStream)); 
            StringBuffer tStringBuffer = new StringBuffer(); 
            String sTempOneLine = new String(""); 
            while ((sTempOneLine = tBufferedReader.readLine()) != null){ 
                tStringBuffer.append(sTempOneLine); 
            } 
           return tStringBuffer.toString(); 
      }catch (Exception ex){ 
           ex.printStackTrace(); 
      } 
  } 
  return null; 
}

Or the following method, the code is as follows :

public class StreamTool {
    /**
     * 把输入流的内容转化成字符串
     * @param is
     * @return
     */
    public static String readInputStream(InputStream is){
        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            int length=0;
            byte[] buffer=new byte[1024];
            while((length=is.read(buffer))!=-1){
                baos.write(buffer, 0, length);
            }
            is.close();
            baos.close();
            //或者用这种方法
            //byte[] result=baos.toByteArray();
            //return new String(result);
            return baos.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }
    }
}

Character input and output stream

Character input stream

java.io.Reader abstraction is the parent class of all character input streams, used to read file content

Character input stream structure:

How to convert strings and input streams in Java

For the convenience of reading, Java provides a convenient class for reading character files.

FileReader class

Construction method:

  • FileReader(File file); Create a new FileReader given a File to read data from.

  • FileReader(String fileName); Creates a new FileReader given the name of a file to read data from.

Commonly used reading methods:

##Method nameDescriptionint read()Read one character, and return -1 if all characters are reached to the endint read(char[] cbuf)Read the read cbuf.length characters into the char arrayint read(char[] cbuf, int off , int len)Read offset off to len characters from this character input stream into the char arrayvoid reset()Reset the streamboolean ready()Judge whether the stream is ready to be readvoid close() Close the character input stream and release all system resourceslong skip(long n)Skip reading n characters and return The number of skipped charactersvoid mark(int readLimit)Mark this input stream. When the reset method is used, it returns to this position and starts reading from this position. Enter characters
#1. Single reading, not recommended if the file is too large.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class dome2{
	public static void main(String[] args){
	  File file=new File("D:/../...txt");   //创建file对象
	  FileReader fr=null;
	  
	  try {
		fr=new FileReader(file);
		int c;  
		while((c=fr.read())!=-1) { 
			System.out.print((char)c);  //强制转换成字符
		}
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		if(fr!=null) {
			try {
				fr.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
   }
}

2. Read multiple characters and output.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class dome2{
	public static void main(String[] args){
	  File file=new File("D:/../...txt");   
	  FileReader fr=null;
	  
	  try {
		fr=new FileReader(file);
		char[] c=new char[100];
		int length;
		while((length=fr.read(c))!=-1) {
			System.out.println(new String(c,0,length));  
		}
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		if(fr!=null) {
			try {
				fr.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
   }
}

Character output stream

java.io.Writer abstract class is the parent class of all character output streams and is used to write data to files.

Character output stream structure:

How to convert strings and input streams in Java

In order to write Java provides a convenient class for character writing.

FileWriter class

Construction method:

  • FileWriter(File file) and FileWriter(String fileName); Construct a FileWriter object using the given file object or the given file path name.

  • FileWriter(File file, boolean append) and FileWriter(String fileName, boolean append); Through the given file object or file The pathname constructs the FileWriter object and whether it is appended or overwritten.

Common reading methods

Method nameDescriptionvoid write(char[] cbuf)Write all character arrays specified by cbuf to the character output streamvoid write(int c)Write a character to the character output streamvoid write(char[] cbuf,int off,int len )Write the characters in the cbuf array from offset off to length len characters into this output stream. void write(String str )Write a string to the character input streamvoid write(String str, int off, int len)Write str string from offset off, length len string to this output stream. Abstract void flush()Refresh the current output stream and force writing of all character dataabstract void close ()Close this output stream
1.writer(int c);Write a character

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class dome2{
	public static void main(String[] args){
	  File file=new File("D:/../...txt");   //创建file对象
       FileWriter  fw=null;
       
       try {
		fw=new FileWriter(file);
		char c='你';
		fw.write((int)c);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		if(fw!=null) {
			try {
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}       
   }
}

2.writer( String str); Write a string

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class dome2{
	public static void main(String[] args){
	  File file=new File("D:/../...txt");   //创建file对象
       FileWriter  fw=null;
       
       try {
		fw=new FileWriter(file);
		String str="你好,java";
		fw.write(str);  //写入一个字符串,等价于write(str,0,str.length);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		if(fw!=null) {
			try {
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}       
   }
}

The above is the detailed content of How to convert strings and input streams in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: Differences between OSJava Platform Independence: Differences between OSMay 16, 2025 am 12:18 AM

There are subtle differences in Java's performance on different operating systems. 1) The JVM implementations are different, such as HotSpot and OpenJDK, which affect performance and garbage collection. 2) The file system structure and path separator are different, so it needs to be processed using the Java standard library. 3) Differential implementation of network protocols affects network performance. 4) The appearance and behavior of GUI components vary on different systems. By using standard libraries and virtual machine testing, the impact of these differences can be reduced and Java programs can be ensured to run smoothly.

Java's Best Features: From Object-Oriented Programming to SecurityJava's Best Features: From Object-Oriented Programming to SecurityMay 16, 2025 am 12:15 AM

Javaoffersrobustobject-orientedprogramming(OOP)andtop-notchsecurityfeatures.1)OOPinJavaincludesclasses,objects,inheritance,polymorphism,andencapsulation,enablingflexibleandmaintainablesystems.2)SecurityfeaturesincludetheJavaVirtualMachine(JVM)forsand

Best Features for Javascript vs JavaBest Features for Javascript vs JavaMay 16, 2025 am 12:13 AM

JavaScriptandJavahavedistinctstrengths:JavaScriptexcelsindynamictypingandasynchronousprogramming,whileJavaisrobustwithstrongOOPandtyping.1)JavaScript'sdynamicnatureallowsforrapiddevelopmentandprototyping,withasync/awaitfornon-blockingI/O.2)Java'sOOPf

Java Platform Independence: Benefits, Limitations, and ImplementationJava Platform Independence: Benefits, Limitations, and ImplementationMay 16, 2025 am 12:12 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM)andbytecode.1)TheJVMinterpretsbytecode,allowingthesamecodetorunonanyplatformwithaJVM.2)BytecodeiscompiledfromJavasourcecodeandisplatform-independent.However,limitationsincludepotentialp

Java: Platform Independence in the real wordJava: Platform Independence in the real wordMay 16, 2025 am 12:07 AM

Java'splatformindependencemeansapplicationscanrunonanyplatformwithaJVM,enabling"WriteOnce,RunAnywhere."However,challengesincludeJVMinconsistencies,libraryportability,andperformancevariations.Toaddressthese:1)Usecross-platformtestingtools,2)

JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.