Java Outputstream to String

OutputStream存为String,OutputStream是输出流,用于输出文件内容,它本身不提供输入操作(也就是说没办法直接将OutputStream存为String)。下面是我找到的两个方法


// method 1:
// 从文件中获取的OutputStream
OutputStream os = new FileOutputStream(fileName);
OutputStreamWriter outw = null;
outw = new OutputStreamWriter(os);


String str = null;      
outw.write(str);
outw.close();
os.flush();
os.close();


// method 2:
// 从文件中获取的OutputStream
OutputStream os = new FileOutputStream(fileName);
ByteArrayOutputStream baos=new ByteArrayOutputStream();  
os.write(baos.toByteArray());  
str = baos.toString(); 
                    
os.flush();
os.close();  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import com.pmstation.spss.DataConstants; import com.pmstation.spss.MissingValue; import com.pmstation.spss.SPSSWriter; import com.pmstation.spss.ValueLabels; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Date; public class Demo { // Entrance point public static void main(String args[]) { try { // Parse the command line if (args.length != 1) { printUsageAndExit(); } // Open file output stream with filename args[0] OutputStream out = new FileOutputStream(args[0]); // Assign SPSS output to the file SPSSWriter outSPSS = new SPSSWriter(out, "utf-8"); // Creating SPSS variable description table outSPSS.setCalculateNumberOfCases(false); outSPSS.addDictionarySection(-1); // Describing varible names and types outSPSS.addStringVar("continent", 255, "Continents of the world"); outSPSS.addNumericVar("size", 8, 2, "Sq km"); outSPSS.addNumericVar("population", 8, 2, "Population"); // Create missing value MissingValue mv = new MissingValue(); mv.setOneDescreteMissingValue(1); outSPSS.addNumericVar("countries", 8, 2, "Number of countries", mv); outSPSS.addDateVar("update", DataConstants.DATE_TYPE_17, "Date of last update", null); // Create value labels ValueLabels valueLabels = new ValueLabels(); valueLabels.putLabel("Asia", "Asia Continent"); valueLabels.putLabel("America", "America Continent"); outSPSS.addValueLabels(1, valueLabels); valueLabels = new ValueLabels(); valueLabels.putLabel(0, "No Countries"); valueLabels.putLabel(23, "Twenty Three Countries"); outSPSS.addValueLabels(4, valueLabels); outSPSS.addStringVar("description", 2200, "Description"); // Create SPSS variable value define table outSPSS.addDataSection(); // Add values for all defined variables
JAVA相关基础知识 1、面向对象的特征有哪些方面 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节。抽象包括两个方面,一是过程抽象,二是数据抽象。 2.继承: 继承是一种联结类的层次模型,并且允许和鼓励类的重用,它提供了一种明确表述共性的方法。对象的一个新类可以从现有的类中派生,这个过程称为类继承。新类继承了原始类的特性,新类称为原始类的派生类(子类),而原始类称为新类的基类(父类)。派生类可以从它的基类那里继承方法和实例变量,并且类可以修改或增加新的方法使之更适合特殊的需要。 3.封装: 封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。面向对象计算始于这个基本概念,即现实世界可以被描绘成一系列完全自治、封装的对象,这些对象通过一个受保护的接口访问其他对象。 4. 多态性: 多态性是指允许不同类的对象对同一消息作出响应。多态性包括参数化多态性和包含多态性。多态性语言具有灵活、抽象、行为共享、代码共享的优势,很好的解决了应用程序函数同名问题。 2、String是最基本的数据类型吗? 基本数据类型包括byte、int、char、long、float、double、boolean和short。 java.lang.String类是final类型的,因此不可以继承这个类、不能修改这个类。为了提高效率节省空间,我们应该用StringBuffer类 3、int 和 Integer 有什么区别 Java 提供两种不同的类型:引用类型和原始类型(或内置类型)。Int是java的原始数据类型,Integer是java为int提供的封装类。Java为每个原始类型提供了封装类。 原始类型封装类 booleanBoolean charCharacter byteByte shortShort intInteger longLong floatFloat doubleDouble 引用类型和原始类型的行为完全不同,并且它们具有不同的语义。引用类型和原始类型具有不同的特征和用法,它们包括:大小和速度问题,这种类型以哪种类型的数据结构存储,当引用类型和原始类型用作某个类的实例数据时所指定的缺省值。对象引用实例变量的缺省值为 null,而原始类型实例变量的缺省值与它们的类型有关。 4、StringStringBuffer的区别 JAVA平台提供了两个类:StringStringBuffer,它们可以储存和操作字符串,即包含多个字符的字符数据。这个String类提供了数值不可改变的字符串。而这个StringBuffer类提供的字符串进行修改。当你知道字符数据要改变的时候你就可以使用StringBuffer。典型地,你可以使用StringBuffers来动态构造字符数据。 5、运行时异常与一般异常有何异同? 异常表示程序运行过程中可能出现的非正常状态,运行时异常表示虚拟机的通常操作中可能遇到的异常,是一种常见运行错误。java编译器要求方法必须声明抛出可能发生的非运行时异常,但是并不要求必须声明抛出未被捕获的运行时异常。 6、说出Servlet的生命周期,并说出Servlet和CGI的区别。 Servlet被服务器实例化后,容器运行其init方法,请求到达时运行其service方法,service方法自动派遣运行与请求对应的doXXX方法(doGet,doPost)等,当服务器决定将实例销毁的时候调用其destroy方法。 与cgi的区别在于servlet处于服务器进程中,它通过多线程方式运行其service方法,一个实例可以服务于多个请求,并且其实例一般不会销毁,而CGI对每个请求都产生新的进程,服务完成后就销毁,所以效率上低于servlet。 7、说出ArrayList,Vector, LinkedList的存储性能和特性 ArrayList和Vector都是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引元素,但是插入元素要涉及数组元素移动等内存操作,所以索引数据快而插入数据慢,Vector由于使用了synchronized方法(线程安全),通常性能上较ArrayList差,而LinkedList使用双向链表实现存储,按序号索引数据需要进行前向或后向遍历,但是插入数据时只需要记录本项的前后项即可,所以插入速度较快。 8、EJB是基于哪些技术实现的?并说出SessionBean和EntityBean的区别,StatefulBean和StatelessBean的区别。 EJB包括Session Bean、Entity Bean、Message Driven Bea
What’s Inside Preface 1 Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4th edition........................ 2 Changes .......................................... 3 Note on the cover design ....... 4 Acknowledgements ................ 4 Introduction 9 Prerequisites .......................... 9 Learning Java ....................... 10 Goals ..................................... 10 Teaching from this book ....... 11 JDK HTML documentation ...................... 11 Exercises ............................... 12 Foundations for Java ............ 12 Source code ........................... 12 Coding standards ......................... 14 Errors .................................... 14 Introduction to Objects 15 The progress of abstraction ........................ 15 An object has an interface ........................... 17 An object provides services ................... 18 The hidden implementation .................... 19 Reusing the implementation ................... 20 Inheritance............................ 21 Is-a vs. is-like-a relationships ......24 Interchangeable objects with polymorphism ............. 25 The singly rooted hierarchy .............................. 28 Containers ............................ 28 Parameterized types (Generics) ..29 Object creation & lifetime ... 30 Exception handling: dealing with errors ............... 31 Concurrent programming ... 32 Java and the Internet .......... 33 What is the Web? ......................... 33 Client-side programming ............ 34 Server-side programming ............ 38 Summary .............................. 38 Everything Is an Object 41 You manipulate objects with references ..................... 41 You must create all the objects ....................... 42 Where storage lives ...................... 42 Special case: primitive types ....... 43 Arrays in Java .............................. 44 You never need to destroy an object .................. 45 Scoping ........................................ 45 Scope of objects ........................... 46 Creating new data types: class ..................................... 46 Fields and methods ..................... 47 Methods, arguments, and return values ................. 48 The argument list ......................... 49 Building a Java program ...... 50 Name visibility ............................. 50 Using other components ............. 50 The static keyword ..................... 51 Your first Java program ....... 52 Compiling and running ............... 54 Comments and embedded documentation ..................... 55 Comment documentation ............ 55 Syntax .......................................... 56 Embedded HTML ........................ 56 Some example tags ...................... 57 Documentation example ............. 59 Coding style .......................... 60 Summary .............................. 60 Exercises .............................. 60 Operators 63 Simpler print statements ..... 63 Using Java operators ........... 64 Precedence ........................... 64 Assignment .......................... 65 Aliasing during method calls ....... 66 Mathematical operators....... 67 Unary minus and plus operators ....................... 68 Auto increment and decrement ............................ 69 Relational operators ............ 70 Testing object equivalence ........... 70 Logical operators .................. 71 Short-circuiting ............................ 72 Literals .................................. 73 Exponential notation ................... 74 Bitwise operators .................. 75 Shift operators ......................76 Ternary if-else operator ......79 String operator + and += .............................. 80 Common pitfalls when using operators ........... 81 Casting operators .................. 81 Truncation and rounding ........... 82 Promotion ................................... 83 Java has no “sizeof” ............. 83 A compendium of operators .......................... 84 Summary ............................... 91 Controlling Execution 93 true and false..................... 93 if-else .................................. 93 Iteration ............................... 94 do-while ..................................... 95 for ................................................ 95 The comma operator................... 96 Foreach syntax ......................97 return ................................. 99 break and continue .......... 99 The infamous “goto” ........... 101 switch ................................104 Summary ............................ 106 Initialization & Cleanup 107 Guaranteed initialization with the constructor ........... 107 Method overloading .......... 109 Distinguishing overloaded methods .................. 110 Overloading with primitives ....... 111 Overloading on return values .... 114 Default constructors ........... 114 The this keyword ............... 116 Calling constructors from constructors ...................... 118 The meaning of static ............... 119 Cleanup: finalization and garbage collection ........ 119 What is finalize() for? ............. 120 You must perform cleanup ......... 121 The termination condition ......... 121 How a garbage collector works .. 122 Member initialization ......... 125 Specifying initialization ............. 126 Constructor initialization ... 127 Order of initialization ................ 127 static data initialization ........... 128 Explicit static initialization ...... 130 Non-static instance initialization ................ 132 Array initialization ............. 133 Variable argument lists ............. 137 Enumerated types ............... 141 Summary ............................ 143 Access Control 145 package: the library unit ................... 146 Code organization ...................... 147 Creating unique package names ........................... 148 A custom tool library .................. 151 Using imports to change behavior ..................... 152 Package caveat ........................... 153 Java access specifiers .......... 153 Package access ........................... 153 public: interface access ............ 154 private: you can’t touch that! .. 155 protected: inheritance access . 156 Interface and implementation .......... 158 Class access ........................ 159 Summary ............................ 162 Reusing Classes 165 Composition syntax ........... 165 Inheritance syntax ............. 168 Initializing the base class ........... 169 Delegation ........................... 171 Combining composition and inheritance ................... 173 Guaranteeing proper cleanup .... 174 Name hiding ............................... 177 Choosing composition vs. inheritance .................... 178 protected ......................... 180 Upcasting ............................ 181 Why “upcasting”? ...................... 181 Composition vs. inheritance revisited ..................................... 182 The final keyword ............. 182 final data ................................... 183 final methods ............................ 186 final classes ............................... 187 final caution .............................. 188 Initialization and class loading ................ 189 Initialization with inheritance ... 189 Summary ............................. 191 Polymorphism 193 Upcasting revisited ............. 193 Forgetting the object type .......... 194 The twist ............................. 196 Method-call binding .................. 196 Producing the right behavior ..... 196 Extensibility ............................... 199 Pitfall: “overriding” private methods ...................... 202 Pitfall: fields and static methods .................. 203 Constructors and polymorphism ................... 204 Order of constructor calls ......... 204 Inheritance and cleanup ........... 206 Behavior of polymorphic methods inside constructors .... 210 Covariant return types ........ 211 Designing with inheritance .................. 212 Substitution vs. extension ......... 213 Downcasting and runtime type information ......... 215 Summary ............................. 217 Interfaces 219 Abstract classes and methods ....................... 219 Interfaces ........................... 222 Complete decoupling ......... 225 “Multiple inheritance” in Java ................................ 230 Extending an interface with inheritance .......................... 231 Name collisions when combining Interfaces ................233 Adapting to an interface .... 234 Fields in interfaces ............ 235 Initializing fields in interfaces .. 236 Nesting interfaces .............. 237 Interfaces and factories ..... 239 Summary ............................. 241 Inner Classes 243 Creating inner classes ........ 243 The link to the outer class .................... 244 Using .this and .new ........ 246 Inner classes and upcasting ..................... 247 Inner classes in methods and scopes ........... 249 Anonymous inner classes ........................ 251 Factory Method revisited .......... 254 Nested classes .................... 256 Classes inside interfaces ............ 257 Reaching outward from a multiplynested class ............... 259 Why inner classes? ............. 259 Closures & callbacks .................. 261 Inner classes & control frameworks ................... 263 Inheriting from inner classes ....................... 269 Can inner classes be overridden? ................... 269 Local inner classes .............. 271 Inner-class identifiers ........ 272 Summary ............................ 273 Holding Your Objects 275 Generics and type-safe containers ........... 276 Basic concepts .................... 278 Adding groups of elements ......................... 279 Printing containers ............ 281 List ..................................... 283 Iterator ............................. 286 ListIterator ............................ 288 LinkedList ....................... 289 Stack ................................. 291 Set ...................................... 292 Map ................................... 295 Queue ................................ 298 PriorityQueue ........................ 299 Collection vs. Iterator ... 301 Foreach and iterators ......... 304 The Adapter Method idiom ...... 306 Summary ............................ 308 Error Handling with Exceptions 313 Concepts ............................. 313 Basic exceptions.................. 314 Exception arguments ................. 315 Catching an exception ........ 315 The try block ............................. 316 Exception handlers .................... 316 Creating your own exceptions ................... 317 Exceptions and logging .............. 319 The exception specification ....................... 322 Catching any exception ..... 323 The stack trace .......................... 324 Rethrowing an exception ........... 325 Exception chaining .................... 327 Standard Java exceptions .......................... 330 Special case: RuntimeException ............... 330 Performing cleanup with finally ....................... 332 What’s finally for? .................... 333 Using finally during return .... 335 Pitfall: the lost exception .......... 336 Exception restrictions ....... 338 Constructors ...................... 340 Exception matching ........... 344 Alternative approaches ...... 345 History ...................................... 346 Perspectives ............................... 347 Passing exceptions to the console ............................ 349 Converting checked to unchecked exceptions ........... 350 Exception guidelines ......... 352 Summary ............................ 352 Strings 355 Immutable Strings ............355 Overloading ‘+’ vs. StringBuilder ................. 356 Unintended recursion ....... 359 Operations on Strings ....... 361 Formatting output ............. 362 printf() .................................... 363 System.out.format() ............ 363 The Formatter class ............... 363 Format specifiers ...................... 364 Formatter conversions ........... 366 String.format() ..................... 368 Regular expressions ........... 370 Basics .........................................370 Creating regular expressions ..... 372 Quantifiers ................................. 374 Pattern and Matcher ............. 375 split() ........................................382 Replace operations .................... 383 reset() .......................................384 Regular expressions and Java I/O .............................. 385 Scanning input ................... 386 Scanner delimiters ................. 388 Scanning with regular expressions ................... 389 StringTokenizer ............. 389 Summary ............................ 391 Type Information 393 The need for RTTI .............. 393 The Class object ................ 395 Class literals ............................... 399 Generic class references ............ 401 New cast syntax ........................ 403 Checking before a cast ....... 404 Using class literals .................... 409 A dynamic instanceof .............. 411 Counting recursively .................. 412 Registered factories ........... 413 instanceof vs. Class equivalence......................... 416 Reflection: runtime class information ................ 417 A class method extractor ........... 418 Dynamic proxies ................ 420 Null Objects ........................ 424 Mock Objects & Stubs ................ 429 Interfaces and type information ................ 430 Summary ............................ 436 Generics 439 Comparison with C++ ........ 440 Simple generics .................. 440 A tuple library ............................ 442 A stack class ............................... 444 RandomList ............................ 445 Generic interfaces .............. 446 Generic methods ................ 449 Leveraging type argument inference ...................450 Varargs and generic methods .... 452 A generic method to use with Generators............ 453 A general-purpose Generator . 453 Simplifying tuple use ................. 455 A Set utility................................ 456 Anonymous inner classes ....................... 459 Building complex models ................. 460 The mystery of erasure ...... 462 The C++ approach .................... 464 Migration compatibility ............ 466 The problem with erasure ......... 467 The action at the boundaries .... 468 Compensating for erasure ........................... 471 Creating instances of types ........ 472 Arrays of generics ...................... 475 Bounds ............................... 479 Wildcards ........................... 482 How smart is the compiler? ...... 484 Contravariance .......................... 485 Unbounded wildcards ............... 488 Capture conversion ................... 492 Issues ................................. 493 No primitives as type parameters .................... 493 Implementing parameterized interfaces ........... 495 Casting and warnings ............... 496 Overloading ............................... 498 Base class hijacks an interface .. 498 Self-bounded types ............ 500 Curiously recurring generics .... 500 Self-bounding ............................ 501 Argument covariance ................ 503 Dynamic type safety .......... 506 Exceptions ......................... 507 Mixins ................................ 509 Mixins in C++ ........................... 509 Mixing with interfaces ............... 510 Using the Decorator pattern ....... 511 Mixins with dynamic proxies .... 512 Latent typing ....................... 514 Compensating for the lack of latent typing ...... 518 Reflection ................................... 518 Applying a method to a sequence .............................. 519 When you don’t happen to have the right interface .......... 521 Simulating latent typing with adapters ............................. 523 Using function objects as strategies ....................... 526 Summary: Is casting really so bad? ...................... 531 Further reading .......................... 533 Arrays 535 Why arrays are special ........535 Arrays are first-class objects ............... 536 Returning an array ............. 539 Multidimensional arrays .................................. 540 Arrays and generics ........... 543 Creating test data ............... 546 Arrays.fill() ............................. 546 Data Generators ...................... 547 Creating arrays from Generators ..................... 551 Arrays utilities .................. 555 Copying an array ........................ 555 Comparing arrays ...................... 556 Array element comparisons ...... 557 Sorting an array .........................560 Searching a sorted array ............ 561 Summary ............................ 564 Containers in Depth 567 Full container taxonomy .... 567 Filling containers ............... 568 A Generator solution .............. 569 Map generators ......................... 570 Using Abstract classes ............. 573 Collection functionality ....................... 580 Optional operations ........... 582 Unsupported operations............ 583 List functionality ............... 586 Sets and storage order ...... 589 SortedSet ................................. 591 Queues ................................ 594 Priority queues ........................... 594 Deques ....................................... 595 Understanding Maps ........ 598 Performance .............................. 599 SortedMap ............................. 602 LinkedHashMap ................... 603 Hashing and hash codes .... 605 Understanding hashCodeQ .... 607 Hashing for speed ...................... 610 Overriding hashCode() ........... 613 Choosing an implementation .............. 617 A performance test framework ........................... 618 Choosing between Lists ............ 621 Microbenchmarking dangers .... 626 Choosing between Sets ............. 627 Choosing between Maps ........... 629 Utilities ............................... 632 Sorting and searching Lists ...... 635 Making a Collection or Map unmodifiable ............... 636 Synchronizing a Collection or Map ................... 637 Holding references ............ 639 The WeakHashMap .............. 640 Java 1.0/1.1 containers ...... 642 Vector & Enumeration ........ 642 Hashtable ............................... 643 Stack ........................................ 643 BitSet ....................................... 644 Summary ............................ 646 I/O 647 The File class .................... 647 A directory lister ........................ 647 Directory utilities ...................... 650 Checking for and creating directories ............. 654 Input and output ............... 656 Types of InputStream ............. 657 Types of OutputStream ......... 658 Adding attributes and useful interfaces .......... 659 Reading from an InputStream with FilterlnputStream ........ 660 Writing to an OutputStream with FilterOutputStream ...... 661 Readers & Writers ......... 662 Sources and sinks of data ......... 662 Modifying stream behavior ...... 663 Unchanged classes .................... 664 Off by itself: RandomAccessFile ....... 665 Typical uses of I/O streams .................... 665 Buffered input file ...................... 665 Input from memory .................. 666 Formatted memory input .......... 667 Basic file output ........................ 668 Storing and recovering data ..... 669 Reading and writing random-access files .................. 670 Piped streams ............................ 672 File reading & writing utilities ............... 672 Reading binary files ................... 674 Standard I/O ....................... 675 Reading from standard input .... 675 Changing System.out to a PrintWriter ...................... 676 Redirecting standard I/O .......... 676 Process control ................... 677 New I/O ............................. 679 Converting data.......................... 681 Fetching primitives ................... 684 View buffers ............................... 685 Data manipulation with buffers ............................... 688 Buffer details ............................. 689 Memory-mapped files ............... 692 File locking ................................. 695 Compression ...................... 698 Simple compression with GZIP .................................. 698 Multifile storage with Zip .......... 699 Java ARchives (JARs) ................ 701 Object serialization ............ 703 Finding the class ........................ 706 Controlling serialization ............ 707 Using persistence ....................... 713 XML .................................... 718 Preferences .......................... 721 Summary ............................ 722 Enumerated Types 725 Basic enum features ......... 725 Using static imports with enums ............................... 726 Adding methods to an enum ........................ 727 Overriding enum methods ....... 728 enums in switch statements ............. 728 The mystery of values() ........................ 729 Implements, not inherits ......................... 732 Random selection .............. 732 Using interfaces for organization .................. 734 Using EnumSet instead of flags ................... 737 Using EnumMap ............. 739 Constant-specific methods .............................. 740 Chain of Responsibility with enums ............................... 743 State machines with enums ..... 746 Multiple dispatching ........... 751 Dispatching with enums .......... 753 Using constant-specific methods ......... 755 Dispatching with EnumMaps ...................... 756 Using a 2-D array ....................... 757 Summary ............................ 759 Annotations 761 Basic syntax ....................... 762 Defining annotations ................. 762 Meta-annotations ...................... 763 Writing annotation processors ........ 765 Annotation elements ................. 765 Default value constraints ........... 766 Generating external files............ 766 Annotations don’t support inheritance ................... 769 Implementing the processor...... 769 Using apt to process annotations ............ 772 Using the Visitor pattern with apt .............................. 775 Annotation-based unit testing .......................... 778 Using @Unit with generics ....... 785 No “suites” necessary .................786 Implementing @Unit ............... 787 Removing test code .................... 792 Summary ............................. 795 Concurrency 797 The many faces of concurrency ....................... 798 Faster execution .........................798 Improving code design ............. 800 Basic threading .................. 801 Defining tasks ............................ 801 The Thread class ..................... 802 Using Executors ..................... 804 Producing return values from tasks ................................. 806 Sleeping ..................................... 808 Priority ...................................... 809 Yielding ...................................... 810 Daemon threads ......................... 810 Coding variations ....................... 814 Terminology ............................... 819 Joining a thread ......................... 819 Creating responsive user interfaces ............................ 821 Thread groups ........................... 822 Catching exceptions .................. 822 Sharing resources .............. 824 Improperly accessing resources ................... 825 Resolving shared resource contention ................... 827 Atomicity and volatility ............. 831 Atomic classes ........................... 836 Critical sections .......................... 837 Synchronizing on other objects .............................. 841 Thread local storage ..................843 Terminating tasks .............. 844 The ornamental garden ............ 844 Terminating when blocked ........ 847 Interruption .............................. 848 Checking for an interrupt .......... 854 Cooperation between tasks ..................... 856 wait() and notifyAll() ............ 857 notify() vs. notifyAll() ........... 861 Producers and consumers ........ 863 Producer-consumers and queues ................................ 868 Using pipes for I/O between tasks ............................. 872 Deadlock ............................. 874 New library components ........................ 879 CountDownLatch .................. 879 CyclicBarrier .......................... 881 DelayQueue ........................... 883 PriorityBlockingQueue....... 885 The greenhouse controller with ScheduledExecutor ...... 887 Semaphore ............................. 890 Exchanger .............................. 893 Simulation .......................... 896 Bank teller simulation .............. 896 The restaurant simulation ........ 900 Distributing work ..................... 904 Performance tuning ........... 909 Comparing mutex technologies ................... 909 Lock-free containers .................. 916 Optimistic locking...................... 922 ReadWriteLocks .................... 923 Active objects ..................... 925 Summary ............................ 929 Further reading .......................... 931 Graphical User Interfaces 933 Applets ............................... 935 Swing basics ....................... 935 A display framework .................. 937 Making a button ................. 938 Capturing an event ............. 939 Text areas ........................... 941 Controlling layout .............. 942 BorderLayout ......................... 942 FlowLayout ............................. 943 GridLayout .............................. 944 GridBagLayout....................... 944 Absolute positioning .................. 945 BoxLayout ............................... 945 The best approach? .................... 945 The Swing event model ..... 945 Event and listener types ........... 946 Tracking multiple events ........... 951 A selection of Swing components ............ 953 Buttons ....................................... 953 Icons .......................................... 955 Tool tips ..................................... 957 Text fields ................................... 957 Borders ....................................... 959 A mini-editor.............................. 959 Check boxes .............................. 960 Radio buttons ............................. 961 Combo boxes (drop-down lists) ...................... 962 List boxes .................................. 963 Tabbed panes ............................. 965 Message boxes ........................... 965 Menus ......................................... 967 Pop-up menus ............................ 972 Drawing ...................................... 973 Dialog boxes ............................... 975 File dialogs .................................978 HTML on Swing components .................... 980 Sliders and progress bars ......... 980 Selecting look & feel ................... 981 Trees, tables & clipboard .......... 983 JNLP and Java Web Start ................... 983 Concurrency & Swing ........ 988 Long-running tasks ................... 988 Visual threading ........................ 994 Visual programming and JavaBeans ................... 996 What is a JavaBean? ................. 996 Extracting Beanlnfo with the Introspector ............ 998 A more sophisticated Bean ..... 1002 JavaBeans and synchronization ....................... 1005 Packaging a Bean .................... 1008 More complex Bean support .. 1009 More to Beans .......................... 1010 Alternatives to Swing ........ 1010 Building Flash Web clients with Flex ................ 1011 Hello, Flex ................................. 1011 Compiling MXML .................... 1012 MXML and ActionScript.......... 1013 Containers and controls........... 1013 Effects and styles ..................... 1015 Events ....................................... 1016
dW 登录 | 注册 IBM developerWorks® 技术主题 软件下载 社区 技术讲座 搜索 developerWorks 打印本页面用电子邮件发送本页面新浪微博人人网腾讯微博搜狐微博网易微博DiggFacebookTwitterDeliciousLinked In developerWorks 中国技术主题Java technology文档库 在 Java 应用程序中访问 USB 设备 介绍 USB、jUSB 和 JSR-80 Java 平台一直都以其平台无关性自豪。虽然这种无关性有许多好处,但是它也使得编写与硬件交互的 Java 应用程序的过程变得相当复杂。在本文中,研究科学家蒋清野讨论了两个项目,它们通过提供使Java 应用程序可以使用 USB 设备的 API 而使这个过程变得更容易。虽然这两个项目仍然处于萌芽状态,但是它们都显示了良好的前景,并已经成为一些实用应用程序的基础。 1 评论: 蒋清野 ([email protected]), 研究科学家, HappyFox Engineering Solutions 2003 年 10 月 25 日 + 内容 在 IBM Bluemix 云平台上开发并部署您的下一个应用。 现在就开始免费试用 通用串行总线(Universal Serial Bus USB)规范的第一个版本发表于 1996年 1月。因为它的低成本、高数据传输率、使用容易和灵活性,USB 在计算机行业里获得了广泛接受。今天,许多周边设备和装置都是通过 USB 接口连接到计算机上的。目前,大多数一般用途的操作系统都提供了对 USB 设备的支持,并且用 C 或者 C++ 可以相对容易地开发访问这些外设的应用程序。不过,Java 编程语言在设计上对硬件访问提供的支持很少,所以编写与 USB 设备交互的应用程序是相当困难的。 IBM 的 Dan Streetman 最早开始了在 Java 语言中提供对 USB 设备的访问的努力。2001年,他的项目通过 Java 规范请求(Java Specification Request,JSR)过程被接受为 Java 语言的候选扩展标准。这个项目现在称为 JSR-80 并且指定了官方包 javax.usb 。同时,在 2000年 6月,Mojo Jojo 和 David Brownell 在 SourceForge 开始了 jUSB 项目。这两个项目都开发出了 Linux 开发人员可以使用的包,尽管它们都还很不完善。这两个项目也都开始试图向其他操作系统上的 Java 应用程序提供对 USB 设备的访问,尽管它们都还没有开发出可以使用的包(参阅 参考资料 中有关本文中讨论的这两个项目及其他项目的资料)。 在本文中,将对 jUSB 和 JSR-80 项目作一个简要介绍,不过,我们首先要看一下 USB 协议的具体细节,这样您就可以理解这两个项目是如何与 USB 设备交互的。我们还将提供代码片段以展示如何用这两个项目的 API 访问 USB 设备。 USB 介绍 1994年,一个由四个行业伙伴(Compaq、Intel、Microsoft 和 NEC)组成的联盟开始制定 USB 协议。该协议最初的目的是将 PC 与电话相连并提供容易扩展和重新配置的 I/O 接口。1996年 1月,发表了 USB 规范的第一个版本,1998年 9月发表了后续版本(版本 1.1)。这个规范允许 127台设备同时连接到一起,总的通信带宽限制为 12 Mbps。后来,又有三个成员(Hewlett-Packard、Lucent 和 Philips)加入了这个联盟。2000年 4月,发表了 USB 规范的 2.0版本,它支持高达 480 Mbps 的传输率。今天,USB 在高速(视频、图像、储存)和全速(音频、宽带、麦克风)数据传输应用中起了关键作用。它还使各种低速设备(键盘、鼠标、游戏外设、虚拟现实外设)连接到 PC 上。 USB 协议有严格的层次结构。在所有 USB 系统中,只有一个主设备,到主计算机的的 USB 接口称为 主控器(host controller)。主控器有两个标准――开放主控器接口(Compaq 的 Open Host Controller Interface,OHCI)和通用主控器接口(Intel 的 Universal Host Controller Interface,UHCI)。这两个标准提供了同样的能力,并可用于所有的 USB 设备,UHCI 的硬件实现更简单一些,但是需要更复杂的设备驱动程序(因而 CPU 的负荷更大一些)。 USB 物理互连是分层的星形拓朴,最多有七层。一个 hub 是每个星形的中心,USB 主机被认为是 root hub。每一段连线都是 hub 与 USB 设备的点对点连接,后者可以是为系统提供更多附加点的另一个 hub,也可以是一个提供功能的某种设备。主机使用主/从协议与 USB 设备通信。这种方式解决了包冲突的问题,但是同时也阻止了附加的设备彼此建立直接通信。 所有传输的数据都是由主控器发起的。数据从主机流向设备称为 下行(downstream)或者 输出(out)传输,数据从设备流向主机称为 上 行(upstream)或者 输入(in)传输。数据传输发生在主机和 USB 设备上特定的 端点(endpoint) 之间,主机与端点之间的数据链接称为 管道(pipe)。 一个给定的 USB 设备可以有许多个端点,主机与设备之间数据管道的数量与该设备上端点的数量相同。一个管道可以是单向或者是双向的,一个管道中的数据流与所有其他管道中的数据流无关。 USB 网络中的通信可以使用下面四种数据传输类型中的任意一种: 控制传输:这些是一些短的数据包,用于设备控制和配置,特别是在设备附加到主机上时。 批量传输:这些是数量相对大的数据包。像扫描仪或者 SCSI 适配器这样的设备使用这种传输类型。 中断传输:这些是定期轮询的数据包。主控器会以特定的间隔自动发出一个中断。 等时传输:这些是实时的数据流,它们对带宽的要求高于可靠性要求。音频和视频设备一般使用这种传输类型。 像串行端口一样,计算机上每一个 USB 端口都由 USB 控制器指定了一个惟一的标识数字(端口 ID)。当 USB 设备附加到 USB 端口上时,就将这个 惟一端口 ID 分配给这台设备,并且 USB 控制器会读取 设备描述符。设备描述符包括适用于该设备的全局信息、以及设备的 配置信息。配置定义了一台 USB 设备的功能和 I/O 行为。一台 USB 设备可以有一个或者多个配置,这由它们相应的配置描述符所描述。每一个配置都有一个或者多个 接口,它可以视为一个物理通信渠道 ;每一个接口有零个或者多个端点,它可以是数据提供者或者数据消费者,或者同时具有这两种身份。接口由接口描述符描述,端点由端点描述符描述。并且一台 USB 设备可能还有字符串描述符以提供像厂商名、设备名或者序列号这样的附加信息。 正如您所看到的,像 USB 这样的协议为使用 Java 这种强调平台和硬件无关性的语言的开发人员提出了挑战。现在让我们看两个试图解决这个问题的项目。 回页首 jUSB API jUSB 项目是由 Mojo Jojo 和 David Brownell 于 2000年 6月创立的。其目标是提供一组免费的、在 Linux 平台上访问 USB 设备的 Java API。这个 API 是按照 Lesser GPL (LGPL)条款发表的,这意味着您可以在专有和免费软件项目中使用它。这个 API 提供了对多个物理 USB 设备的多线程访问,并支持本机和远程设备。具有多个接口的设备可以同时被多个应用程序(或者设备驱动程序)所访问,其中每一个应用程序(或者设备驱动程序)都占据一个不同的接口。该 API 支持控制传输、批量传输和中断传输,不支持等时传输,因为等时传输用于媒体数据(如音频和视频),JMF API 已经在其他标准设备驱动程序上对此提供了很好的支持(参阅 参考资料)。当前,该 API 可以在具有 Linux 2.4 核心或者以前的 2.2.18 核心的 GNU/Linux 版本上工作。因此可支持大多数最新的版本,例如,该 API 可以在没有任何补丁或者升级的 Red Hat 7.2 和 9.0 上工作。 jUSB API 包括以下包: usb.core : 这个包是 jUSB API 的核心部分。它使得 Java 应用程序可以从 USB 主机访问 USB 设备。 usb.linux : 这个包包含 usb.core.Host 对象的 Linux 实现、bootstrapping 支持和其他可以提升 Linux USB 支持的类。这个实现通过虚拟 USB 文件系统( usbdevfs )访问 USB 设备。 usb.windows : 这个包包含 usb.core.Host 对象的 Windows 实现、bootstrapping 支持和其他可以提升 Windows USB 支持的类。这个实现仍然处于非常初级的阶段。 usb.remote : 这个包是 usb.core API 的远程版本。它包括一个 RMI proxy 和一个 daemon 应用程序,它让 Java 应用程序可以访问远程计算机上的 USB 设备。 usb.util : 这个包提供了一些有用的实用程序,可以将 firmware下载到 USB 设备上、将 USB 系统的内容储到 XML 中、以及将只有 bulk I/O 的 USB 设备工具换成一个套接字(socket)。 usb.devices : 这个可选包收集了用 jUSB API 访问不同 USB 设备的 Java 代码,包括柯达数码相机和 Rio 500 MP3 播放器。这些 API 经过特别编写以简化访问特定 USB 设备的过程,并且不能用于访问其他设备。这些 API 是在 usb.core API 之上构建的,它们可以工作在所有支持 jUSB 的操作系统上。 usb.view : 这个可选包提供了基于 Swing 的 USB 树简单浏览器。它是一个展示 jUSB API 应用的很好的示例程序。 尽管 usb.core.Host 对象的实现对于不同的操作系统是不同的,但是 Java 程序员只需要理解 usb.core 包就可以用 jUSB API 开始应用程序的开发。表 1 列出了 usb.core 的接口和类,Java 程序员应该熟悉它们: 表 1. jUSB 中的接口和类 接口 说明 Bus 将一组 USB 设备连接到 Host 上 Host 表示具有一个或者多个 Bus 的 USB 控制器 类 说明 Configuration 提供对设备所支持的 USB 配置的访问,以及对与该配置关联的接口的访问 Descriptor 具有 USB 类型的描述符的实体的基类 Device 提供对 USB 设备的访问 DeviceDescriptor 提供对 USB 设备描述符的访问 EndPoint 提供对 USB 端点描述符的访问、在给定设备配置中构造设备数据输入或者输出 HostFactory 包含 bootstrapping 方法 Hub 提供对 USB hub 描述符以及一些 hub 操作的访问 Interface 描述一组端点,并与一个特定设备配置相关联 PortIdentifier 为 USB 设备提供稳定的字符串标识符,以便在操作和故障诊断时使用 用 jUSB API 访问一台 USB 设备的正常过程如下: 通过从 HostFactory 得到 USB Host 进行 Bootstrap。 从 Host 访问 USB Bus ,然后从这个 Bus 访问 USB root hub(即 USB Device )。 得到 hub 上可用的 USB 端口数量,遍历所有端口以找到正确的 Device 。 访问附加到特定端口上的 USB Device 。可以用一台 Device 的 PortIdentifier 直接从 Host 访问它,也可以通过从 root hub 开始遍历 USB Bus 找到它。 用 ControlMessage 与该 Device 直接交互,或者从该 Device 的当前 Configuration 中要求一个 Interface, 并与该 Interface 上可用的 Endpoint 进行 I/O 。 清单 1 展示了如何用 jUSB API 获得 USB 系统中的内容。这个程序编写为只是查看 root hub 上可用的 USB 设备,但是很容易将它改为遍历整个 USB 树。这里的逻辑对应于上述步骤 1 到步骤 4。 清单 1. 用 jUSB API 获得 USB 系统的内容 import usb.core.*; public class ListUSB { public static void main(String[] args) { try { // Bootstrap by getting the USB Host from the HostFactory. Host host = HostFactory.getHost(); // Obtain a list of the USB buses available on the Host. Bus[] bus = host.getBusses(); int total_bus = bus.length; // Traverse through all the USB buses. for (int i=0; i<total_bus; i++) { // Access the root hub on the USB bus and obtain the // number of USB ports available on the root hub. Device root = bus[i].getRootHub(); int total_port = root.getNumPorts(); // Traverse through all the USB ports available on the // root hub. It should be mentioned that the numbering // starts from 1, not 0. for (int j=1; j<=total_port; j++) { // Obtain the Device connected to the port. Device device = root.getChild(j); if (device != null) { // USB device available, do something here. } } } } catch (Exception e) { System.out.println(e.getMessage()); } } 清单 2 展示了在应用程序成功地找到了 Device 的条件下,如何与 Interface 和 EndPoint 进行批量 I/O。 这个代码段也可以修改为执行控制或者中断 I/O。它对应于上述步骤 5。 清单 2. 用 jUSB API 执行批量 I/O if (device != null) { // Obtain the current Configuration of the device and the number of // Interfaces available under the current Configuration. Configuration config = device.getConfiguration(); int total_interface = config.getNumInterfaces(); // Traverse through the Interfaces for (int k=0; k<total_interface; k++) { // Access the currently Interface and obtain the number of // endpoints available on the Interface. Interface itf = config.getInterface(k, 0); int total_ep = itf.getNumEndpoints(); // Traverse through all the endpoints. for (int l=0; l<total_ep; l++) { // Access the endpoint, and obtain its I/O type. Endpoint ep = itf.getEndpoint(l); String io_type = ep.getType(); boolean input = ep.isInput(); // If the endpoint is an input endpoint, obtain its // InputStream and read in data. if (input) { InputStream in; in = ep.getInputStream(); // Read in data here in.close(); } // If the Endpoint is and output Endpoint, obtain its // OutputStream and write out data. else { OutputStream out; out = ep.getOutputStream(); // Write out data here. out.close(); } } } } jUSB 项目在 2000年 6月到 2001年 2月期间非常活跃。该 API 的最新的版本 0.4.4发表于 2001年 2月 14日。从那以后只提出了很少的改进,原因可能是 IBM 小组成功地成为了 Java 语言的候选扩展标准。不过,基于 jUSB 已经开发出一些第三方应用程序,包括 JPhoto 项目(这是一个用 jUSB 连接到数码照相机的应用程序)和 jSyncManager 项目(这是一个用 jUSB 与使用 Palm 操作系统的 PDA 同步的应用程序)。 回页首 JSR-80 API (javax.usb) 正如前面提到的,JSR-80 项目是由 IBM 的 Dan Streetman 于 1999年创立的。2001年,这个项目通过 Java 规范请求(JSR)过程被接受为 Java 语言的候选扩展标准。这个项目现在称为 JSR-80 并且被正式分派了 Javajavax.usb 。这个项目使用 Common Public License 的许可证形式,并通过 Java Community Process 进行开发。这个项目的目标是为 Java 平台开发一个 USB 接口,可以从任何 Java 应用程序中完全访问 USB 系统。JSR-80 API 支持 USB 规范所定义的全部四种传输类型。目前,该 API 的 Linux 实现可以在支持 2.4 核心的大多数最新 GNU/Linux 版本上工作,如 Red Hat 7.2 和 9.0。 JSR-80 项目包括三个包: javax-usb ( javax.usb API)、 javax-usb-ri (操作系统无关的基准实现的公共部分)以及 javax-usb-ri-linux (Linux 平台的基准实现,它将公共基准实现链接到 Linux USB 堆栈)。所有这三个部分都是构成 Linux 平台上 java.usb API 完整功能所必需的。在该项目的电子邮件列表中可以看到有人正在致力于将这个 API 移植到其他操作系统上(主要是 Microsoft Windows),但是还没有可以工作的版本发表。 尽管 JSR-80 API 的操作系统无关的实现在不同的操作系统上是不同的,但是 Java 程序员只需要理解 javax.usb 包就可以开始开发应用程序了。表 2 列出了 javax.usb 中的接口和类, Java 程序员应该熟悉它们: 表 2. JSR-80 API 中的接口和类 接口 说明 UsbConfiguration 表示 USB 设备的配置 UsbConfigurationDescriptor USB 配置描述符的接口 UsbDevice USB 设备的接口 UsbDeviceDescriptor USB 设备描述符的接口 UsbEndpoint USB 端点的接口 UsbEndpointDescriptor USB 端点描述符的接口 UsbHub USB hub 的接口 UsbInterface USB 接口的接口 UsbInterfaceDescriptor USB 接口描述符的接口 UsbPipe USB 管道的接口 UsbPort USB 端口的接口 UsbServices javax.usb 实现的接口 类 说明 UsbHostManager javax.usb 的入口点 用 JSR-80 API 访问 USB 设备的正常过程如下: 通过从 UsbHostManager 得到相应的 UsbServices 进行 Bootstrap。 通过 UsbServices 访问 root hub。在应用程序中 root hub 就是一个 UsbHub 。 获得连接到 root hub 的 UsbDevice s 清单。遍历所有低级 hub 以找到正确的 UsbDevice 。 用控制消息( UsbControlIrp )与 UsbDevice 直接交互,或者从 UsbDevice 的相应 UsbConfiguration 中要求一个 UsbInterface 并与该 UsbInterface 上可用的 UsbEndpoint 进行 I/O。 如果一个 UsbEndpoint 用于进行 I/O,那么打开与它关联的 UsbPipe 。通过这个 UsbPipe 可以同步或者异步提交上行数据(从 USB 设备到主计算机)和下行数据(从主计算机到 USB 设备)。 当应用程序不再需要访问该 UsbDevice 时,关闭这个 UsbPipe 并释放相应的 UsbInterface 。 在清单 3 中,我们用 JSR-80 API 获得 USB 系统的内容。这个程序递归地遍历 USB 系统上的所有 USB hub 并找出连接到主机计算机上的所有 USB 设备。这段代码对应于上述步骤 1 到步骤 3。 清单 3. 用 JSR-80 API 获得 USB 系统的内容 import javax.usb.*; import java.util.List; public class TraverseUSB { public static void main(String argv[]) { try { // Access the system USB services, and access to the root // hub. Then traverse through the root hub. UsbServices services = UsbHostManager.getUsbServices(); UsbHub rootHub = services.getRootUsbHub(); traverse(rootHub); } catch (Exception e) {} } public static void traverse(UsbDevice device) { if (device.isUsbHub()) { // This is a USB Hub, traverse through the hub. List attachedDevices = ((UsbHub) device).getAttachedUsbDevices(); for (int i=0; i<attachedDevices.size(); i++) { traverse((UsbDevice) attachedDevices.get(i)); } } else { // This is a USB function, not a hub. // Do something. } } } 清单 4 展示了在应用程序成功地找到 Device 后,如何与 Interface 和 EndPoint 进行 I/O。这段代码还可以修改为进行所有四种数据传输类型的 I/O。它对应于上述步骤 4 到步骤 6。 清单 4. 用 JSR-80 API 进行 I/O public static void testIO(UsbDevice device) { try { // Access to the active configuration of the USB device, obtain // all the interfaces available in that configuration. UsbConfiguration config = device.getActiveUsbConfiguration(); List totalInterfaces = config.getUsbInterfaces(); // Traverse through all the interfaces, and access the endpoints // available to that interface for I/O. for (int i=0; i<totalInterfaces.size(); i++) { UsbInterface interf = (UsbInterface) totalInterfaces.get(i); interf.claim(); List totalEndpoints = interf.getUsbEndpoints(); for (int j=0; j<totalEndpoints.size(); j++) { // Access the particular endpoint, determine the direction // of its data flow, and type of data transfer, and open the // data pipe for I/O. UsbEndpoint ep = (UsbEndpoint) totalEndpoints.get(i); int direction = ep.getDirection(); int type = ep.getType(); UsbPipe pipe = ep.getUsbPipe(); pipe.open(); // Perform I/O through the USB pipe here. pipe.close(); } interf.release(); } } catch (Exception e) {} } JSR-80 项目从一开始就非常活跃。2003年 2月发表了 javax.usb API、RI 和 RI 的 0.10.0 版本。看起来这一版本会提交给 JSR-80 委员会做最终批准。预计正式成为 Java 语言的扩展标准后,其他操作系统上的实现会很快出现。Linux 开发者团体看来对 JSR-80 项目的兴趣比 jUSB 项目更大,使用 Linux 平台的 javax.usb API 的项目数量在不断地增加。 回页首 结束语 jUSB API 和 JSR-80 API 都为应用程序提供了从运行 Linux 操作系统的计算机中访问 USB 设备的能力。JSR-80 API 提供了比 jUSB API 更多的功能,很有可能成为 Java 语言的扩展标准。目前,只有 Linux 开发人员可以利用 jUSB 和 JSR-80 API 的功能。不过,有人正在积极地将这两种 API 移植到其他操作系统上。Java 开发人员应该在不久就可以在其他操作系统上访问 USB 设备。从现在起就熟悉这些 API,当这些项目可以在多个平台上发挥作用时,您就可以在自己的应用程序中加入 USB 功能了。 参考资料 您可以参阅本文在 developerWorks 全球站点上的 英文原文. 有关 USB 规范的更多信息,请访问 USB.org。 访问 SourceForge 上的 jUSB 项目主页。 有关 JSR-80 项目的更多信息,请访问其 主页或者其 在 Java Community Process 中的页面。 查找更多有关 jPhoto 项目的内容。 了解 jSyncManager项目。 有关 JMF 项目的更多内容,参阅 Eric Olson 的全面性的“ Java Media Framework 基础”教程( developerWorks,2002年 5月)。 可以在 developerWorks Java 技术专区 中找到关于 Java 编程各个方面的数百篇文章。 加入 developerWorks 中文社区,查看开发人员推动的博客、论坛、组和维基,并与其他 developerWorks 用户交流。 条评论 请 登录 或 注册 后发表评论。 添加评论: 注意:评论中不支持 HTML 语法 有新评论时提醒我剩余 1000 字符 共有评论 (1) 非常不错! 由 javaku 于 2012年05月28日发布 报告滥用 IBM PureSystems IBM PureSystems™ 系列解决方案是一个专家集成系统 developerWorks 学习路线图 通过学习路线图系统掌握软件开发技能 软件下载资源中心 软件下载、试用版及云计算 回页首 帮助 联系编辑 提交内容 订阅源 在线浏览每周时事通讯 新浪微博 报告滥用 使用条款 第三方提示 隐私条约 浏览辅助 IBM 教育学院教育培养计划 IBM 创业企业全球扶持计划 ISV 资源 (英语) dW 中国每周时事通讯 选择语言: English 中文 日本語

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值