New I/0 Functionality for JavaTM 2 Standard Edition 1.4

印尼稻米收成与粮食安全数据集2026年 本数据集收录印度尼西亚2026年水稻收成与粮食安全遥测数据,包含10000条稻米农业收成产量与粮食安全监测记录,围绕印尼国家粮食安全体系中的核心作物水稻展开。稻米是印尼逾两亿人口的主粮,其收成波动直接影响国家粮食安全与进口政策,本数据集将种植区域、收成产量、气候与土壤相关遥测指标整合为结构化表格,可支撑粮食产量预测、收成影响因素分析、区域粮食安全评估与农业政策模拟等研究任务。典型应用场景包括:农业时间序列产量预测模型构建、气候因子与水稻收成的关联分析、省份与地区层面的粮食自给率测算、粮食安全风险预警指标设计,也可作为农业经济、粮食政策与数据科学交叉课程的教学素材。数据为2026年最新版,规模约1.2MB、单CSV结构规整,字段命名清晰,适合Python、Pandas、Scikit-learn等主流工具链直接使用,便于开展探索性分析、可视化与机器学习全流程练习。重要说明:本数据为遥测整理数据,分析结论以数据集文档口径为准,农业决策请结合官方统计综合研判。许可:CC0公有领域,可自由使用与二次分发。 立即下载

New I/0 Functionality for JavaTM 2 Standard Edition 1.4

John Zukowski
October, 2001

Back in January 2000, while many people were arguing about whether the year 2000 was the last or first year of the century, life began for JSR 51 as an approved Java Specification Request (JSR). The name of that JSR is New I/O APIs for the Java Platform. Many people think of the new capabilities as just offering non-blocking I/O operations. However, the new features introduced into the JavaTM 2 Platform, Standard Edition (J2SETM), version 1.4 Beta, include many other new and interesting features. While the API certainly will offer support for scalable I/O operations for both sockets and files, you'll also find a regular expression package for pattern matching, encoders and decoders for character set conversions, and improved file system support like file locking and memory mapping. All four of these new features will be covered in this article.

Note: The Java Native Interface (JNI) changes made to support the New I/O operations will not be covered. For information on these changes, see the Resources section at the end of this article.

Buffers

Starting from the simplest and building up to the most complex, the first improvement to mention is the set of Buffer classes found in the java.nio package. These buffers provide a mechanism to store a set of primitive data elements in an in-memory container. Basically, imagine wrapping a combined DataInputStream/DataOutputStream around a fixed-size byte array and then only being able to read and write one data type, like char, int, or double. There are seven such buffers available:

  • ByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

The ByteBuffer actually supports reading and writing the other six types, but the others are type specific. To demonstrate the use of a buffer, the following snippet converts a String to a CharBuffer and reads a character at a time. You convert the String to a CharBuffer with the wrap method, then get each letter with the get method.

CharBuffer buff = CharBuffer.wrap(args[0]);
for (int i=0, n=buff.length(); i<n; i++) {
  System.out.println(buff.get());
}

When using buffers, it is important to realize there are different sizing and positioning values to worry about. The length method is actually non-standard, specific to CharBuffer. There is nothing wrong with it, but it really reports the remaining length, so if the position is not at the beginning, the reported length will not be the buffer length, but the number of remaining characters within the buffer. In other words, the above loop can also be written as follows.

CharBuffer buff = CharBuffer.wrap(args[0]);
for (int i=0; buff.length() > 0; i++) {
  System.out.println(buff.get());
}

Getting back to the different sizing and positioning values, the four values are known as mark, position, limit, and capacity:

  • mark -- setable position with mark method that can be used to reset the position with reset, <= position, >= 0
  • position -- current read/write position within buffer, <= limit
  • limit -- index of first element that should not be read, <= capacity
  • capacity -- size of buffer, >= limit

The position is an important piece of information to keep in mind when reading from and writing to a buffer. For instance, if you want to read what you just wrote you must move the position to where you want to read from, otherwise, you'll read past the limit and get whatever just happens to be there. This is where the flip method comes in handy, changing the limit to the current position and moving the current position to zero. You can also rewind a buffer to keep the current limit and move the position back to zero. For example, removing the flip call from the following snippet will get back a space, assuming nothing was put in the buffer originally.

buff.put('a');
buff.flip();
buff.get();

The wrap mechanism shown above is an example of a non-direct buffer. Non-direct buffers can also be created and sized with the allocate method, essentially wrapping the data into an array. At a slightly higher creation cost, you can also create a contiguous memory block, also called a direct buffer, with the allocateDirect method. Direct buffers rely on the system's native I/O operations to optimize access operations.

Mapped Files

There is one specialized form of direct ByteBuffer known as a MappedByteBuffer. This class represents a buffer of bytes mapped to a file. To map a file to a MappedByteBuffer, you first must get the channel for a file. A channel represents a connection to something, such as a pipe, socket, or file, that can perform I/O operations. In the case of a FileChannel, you can get one from a FileInputStream, FileOutputStream, or RandomAccessFile through the getChannel method. Once you have the channel, you map it to a buffer with map, specifying the mode and portion of the file you want to map. The file channel can be opened read-only (MAP_RO), copy-on-write (MAP_COW), or read-write (MAP_RW).

Here's the basic process for creating a read-only MappedByteBuffer from a file:

String filename = ...;
FileInputStream input = new 
  FileInputStream(filename);
FileChannel channel = input.getChannel();
int fileLength = (int)channel.size();
MappedByteBuffer buffer = 
  channel.map(FileChannel.MAP_RO, 0, fileLength);

You'll find the channel-related classes in the java.nio.channels package.

Once the MappedByteBuffer has been created, you can access it like any other ByteBuffer. In this particular case though, it is read-only, so any attempt to put something will throw an exception, NonWritableChannelException in this case. If you need to treat the bytes as characters, you must convert the ByteBuffer into a CharBuffer through the use of a character set for the conversion. This character set is specified by the Charset class. You then decode the file contents through the CharsetDecoder class. There is also a CharsetEncoder to go in the other direction.

// ISO-8859-1  is ISO Latin Alphabet #1
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buffer);

These classes are found in the java.nio.charset package.

Regular Expressions

Once you've mapped the input file to a CharBuffer, you can do pattern matching on the file contents. Think of running grep or wc on the file to do regular expression matching or word counting, respectively. That's where the java.util.regex package comes into play and the Pattern and Matcher classes get used.

The Pattern class provides a whole slew of constructs for matching regular expressions. Basically, you provide the pattern as a String. See the class documentation for full details of the patterns. Here are some samples to get you started:

  • Line pattern, any number of characters followed by carriage return and/or line feed: .*/r?/n or .*$
  • Series of numbers: [0-9]* or /d*
  • A control character {cntrl}
  • An upper or lowercase US-ASCII character, followed by white space, followed by punctuation: [{lower}{upper}]/s{punct}

When you provide the pattern, you tell the Pattern class to compile it. Because pattern matching tries to find the largest possible match, in the case of the end-of-line character ($), you don't want to match the entire file to the end of it. You must use the compile option of MULTILINE. There are other options for tasks like case-insensitive matching and Unicode-aware case folding, among a few others. So, if your pattern was for the line pattern above, the code would look like such:

Pattern linePattern = Pattern.compile(".*$", 
  Pattern.MULTILINE);

When it is time to match the pattern, you call the matcher method to get a Matcher back. From this, you can find out if the pattern matches or find and get the matching piece with group, or you can split the string by providing the break pattern, and getting the individual pieces back with split. For instance, the following is a framework for reading a line at a time and getting words out of each line.

Matcher matcher = p.matcher(aString);
Pattern wordBreakPattern = 
  Pattern.compile("[{space}{punct}]");
// Loop through the lines
while (lineMatcher.find()) {
  CharSequence line = lineMatcher.group();
  String words[] = wordBreakPattern.split(line);

  // For each word
  for (int i=0, n=words.length; i<n; i++) {
    // Lines with just break characters return an empty string
    if (words[i].length() > 0) {
      System.out.println(":" + words[i] + ":");
    }
  }
}

There is also a shortcut for matching with boolean b = Pattern.matches(".*/r?/n", aString), but it isn't efficient for when you need to recheck for matches as the Pattern is not compiled.

To combine all the previously mentioned skills, the following example performs a word/line count on file passed into the program:

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;

public class WordCount {
  public static void main(String args[]) throws 
    Exception { 
      String filename = args[0];

    // Map File from filename to byte buffer
    FileInputStream input = new 
      FileInputStream(filename);
    FileChannel channel = input.getChannel();
    int fileLength = (int)channel.size();
    MappedByteBuffer buffer = 
      channel.map(FileChannel.MAP_RO, 0, 
        fileLength);

    // Convert to character buffer
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);

    // Create line pattern
    Pattern linePattern = Pattern.compile(".*$",
      Pattern.MULTILINE);

    // Create word pattern
    Pattern wordBreakPattern = 
      Pattern.compile("[{space}{punct}]");

    // Match line pattern to buffer
    Matcher lineMatcher = 
      linePattern.matcher(charBuffer);

    Map map = new TreeMap();
    Integer ONE = new Integer(1);

    // For each line
    while (lineMatcher.find()) {
      // Get line
      CharSequence line = lineMatcher.group();

      // Get array of words on line
      String words[] = wordBreakPattern.split(line);

      // For each word
      for (int i=0, n=words.length; i<n; i++) {
        if (words[i].length() > 0) {
          Integer frequency = 
            (Integer)map.get(words[i]);
          if (frequency == null) {
            frequency = ONE;
          } else {
            int value = frequency.intValue();
            frequency = new Integer(value + 1);
          }
          map.put(words[i], frequency);
        }
      }
    }
    System.out.println(map);
  }
}

For additional information about the regular expression library, see the Regular Expressions and the Java Programming Language article referenced in the Resources.

Socket Channels

Moving on from file channels takes us to channels for reading from and writing to socket connections. These channels can be used in a blocking or non-blocking fashion. In the blocking fashion, they just replace the call to connect or accept, depending on whether you are a client or a server. In the non-blocking fashion, there is no equivalent.

The new classes to deal with for basic socket reading and writing are the InetSocketAddress class in the java.net package to specify where to connect to, and the SocketChannel class in the java.nio.channels package to do the actual reading and writing operations.

Connecting with InetSocketAddress is very similar to working with the Socket class. All you have to do is provide the host and port:

String host = ...;
InetSocketAddress socketAddress = new 
  InetSocketAddress(host, 80);

Once you have the InetSocketAddress, that's where life changes. Instead of reading from the socket's input stream and writing to the output stream, you need to open a SocketChannel and connect it to the InetSocketAddress:

SocketChannel channel = SocketChannel.open();
channel.connect(socketAddress);

Once connected, you can read from or write to the channel with ByteBuffer objects. For instance, you can wrap a String in a CharBuffer with the help of an CharsetEncoder to send an HTTP request:

Charset charset = Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
String request = "GET / /n/r/n/r";
channel.write(encoder.encode(CharBuffer.wrap(request)));

You can then read the response from the channel. Since the response for this HTTP request will be text, you'll need to convert that response into a CharBuffer through a CharsetDecoder. By creating just a CharBuffer to start, you can keep reusing the object to avoid unnecessary garbage collection between reads:

ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
CharBuffer charBuffer = CharBuffer.allocate(1024);
while ((channel.read(buffer)) != -1) {
  buffer.flip();
  decoder.decode(buffer, charBuffer, false);
  charBuffer.flip();
  System.out.println(charBuffer);
  buffer.clear();
  charBuffer.clear();
}

The following program connects all these pieces to read the main page of a Web site through an HTTP request. Feel free to save the output to a file to compare the results to viewing the page with a browser.

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;


public class ReadURL {
  public static void main(String args[]) {
    String host = args[0];
    SocketChannel channel = null;

    try {

      // Setup
      InetSocketAddress socketAddress = 
        new InetSocketAddress(host, 80);
      Charset charset = 
        Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = 
        charset.newDecoder();
      CharsetEncoder encoder = 
        charset.newEncoder();

      // Allocate buffers
      ByteBuffer buffer = 
        ByteBuffer.allocateDirect(1024);
      CharBuffer charBuffer = 
        CharBuffer.allocate(1024);

      // Connect
      channel = SocketChannel.open();
      channel.connect(socketAddress);

      // Send request
      String request = "GET / /n/r/n/r";
      channel.write(encoder.encode(CharBuffer.wrap(request)));

      // Read response
      while ((channel.read(buffer)) != -1) {
        buffer.flip();
        // Decode buffer
        decoder.decode(buffer, charBuffer, false);
        // Display
        charBuffer.flip();
        System.out.println(charBuffer);
        buffer.clear();
        charBuffer.clear();
      }
    } catch (UnknownHostException e) {
      System.err.println(e);
    } catch (IOException e) {
      System.err.println(e);
    } finally {
      if (channel != null) {
        try {
          channel.close();
        } catch (IOException ignored) {
        }
      }
    }
  }
}

Non-Blocking Reads

Now comes the interesting part, and what people are most interested in in the new I/O packages. How do you configure the channel connection to non-blocking? The basic step is to call the configureBlocking method on the opened SocketChannel, and pass in a value of false. Once you call the connect method, the method now returns immediately.

String host = ...;
InetSocketAddress socketAddress = 
  new InetSocketAddress(host, 80);
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(socketAddress);

Once you have a non-blocking channel, you then have to figure out how to actually work with the channel. The SocketChannel is an example of a SelectableChannel. These selectable channels work with a Selector. Basically, you register the channel with the Selector, tell the Selector what events you are interested in, and it notifies you when something interesting happens.

To get a Selector instance, just call the static open method of the class:

Selector selector = Selector.open();

Registering with the Selector is done through the register method of the channel. The events are specified by fields of the SelectionKey class. In the case of the SocketChannel class, the available operations are OP_CONNECT, OP_READ, and OP_WRITE. So, if you were interested in read and connection operations, you would register as follows:

channel.register(selector, 
  SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

At this point, you have to wait on the selector to tell you when events of interest happen on registered channels. The select method of the Selector will block until something interesting happens. To find this out, you can put a while (selector.select() > 0) loop in its own thread and then go off and do your own thing while the I/O events are being processed. The select method returns when something happens, where the value returned is the count of channels ready to be acted upon. This value doesn't really matter though.

Once something interesting happens, you have to figure out what happened and respond accordingly. For the channel registered here with the selector, you expressed interest in both the OP_CONNECT and OP_READ operations, so you know it can only be one of those events. So, what you do is get the Set of ready objects through the selectedKeys method, and iterate. The element in the Set is a SelectionKey, and you can check if it isConnectable or isReadable for the two states of interest.

Here's the basic framework of the loop so far:

while (selector.select(500) > 0) {
  // Get set of ready objects
  Set readyKeys = selector.selectedKeys();
  Iterator readyItor = readyKeys.iterator();

  // Walk through set
  while (readyItor.hasNext()) {

    // Get key from set
    SelectionKey key = 
      (SelectionKey)readyItor.next();

    // Remove current entry
    readyItor.remove();

    // Get channel
    SocketChannel keyChannel = 
      (SocketChannel)key.channel();

    if (key.isConnectable()) {

    } else if (key.isReadable()) {

    }
  }
}

The remove method call requires a little explanation. The ready set of channels can change while you are processing them. So, you should remove the one you are processing when you process it. There's also a timeout setup here for the select call so it doesn't wait forever if there is nothing to do. There's also a call to get the channel from the key in there. You'll need that for each operation.

For the sample program here you're doing the equivalent of reading from an HTTP connection, so upon connection you need to send the initial HTTP request. Basically, once you know the connection is made, you send a GET request for the root of the site. When the selector reports that the channel is connectable, it may not have finished connecting yet. So, you should always check if the connection is pending through isConnectionPending and call finishConnect if it is. Once connected, you can write to the channel, but must use a ByteBuffer, not the more familiar I/O streams.

Here's what the connection code looks like:

// OUTSIDE WHILE LOOP
Charset charset = 
     Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();

// INSIDE if (channel.isConnectable())
// Finish connection
if (keyChannel.isConnectionPending()) {
  keyChannel.finishConnect();
}

// Send request
String request = "GET / /n/r/n/r";
keyChannel.write
     (encoder.encode(CharBuffer.wrap(request)));

The reading from a socket channel is just like from a file channel. There is one exception though. It is more likely that the buffer may not be full when reading from a socket. Not a big deal though, as you are just going to read what is ready.

// OUTSIDE WHILE LOOP
CharsetDecoder decoder = charset.newDecoder();
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
CharBuffer charBuffer = CharBuffer.allocate(1024);

// INSIDE if (channel.isReadable())
// Read what's ready in response
keyChannel.read(buffer);
buffer.flip();

// Decode buffer
decoder.decode(buffer, charBuffer, false);

// Display
charBuffer.flip();
System.out.print(charBuffer);

// Clear for next pass
buffer.clear();
charBuffer.clear();

Add in the necessary exception handling code and you have your socket reader. Be sure to close the channel in the finally clause to make sure its resources are released, even if there is an exception. Here's the complete client code:

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;


public class NonBlockingReadURL {
  static Selector selector;

  public static void main(String args[]) {
    String host = args[0];
    SocketChannel channel = null;

    try {

      // Setup
      InetSocketAddress socketAddress = 
        new InetSocketAddress(host, 80);
      Charset charset = 
        Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = 
        charset.newDecoder();
      CharsetEncoder encoder = 
        charset.newEncoder();

      // Allocate buffers
      ByteBuffer buffer = 
        ByteBuffer.allocateDirect(1024);
      CharBuffer charBuffer = 
        CharBuffer.allocate(1024);

      // Connect
      channel = SocketChannel.open();
      channel.configureBlocking(false);
      channel.connect(socketAddress);

      // Open Selector
      selector = Selector.open();

      // Register interest in when connection
      channel.register(selector, 
        SelectionKey.OP_CONNECT | 
          SelectionKey.OP_READ);

      // Wait for something of interest to happen
      while (selector.select(500) > 0) {
        // Get set of ready objects
        Set readyKeys = selector.selectedKeys();
        Iterator readyItor = readyKeys.iterator();

        // Walk through set
        while (readyItor.hasNext()) {

          // Get key from set
          SelectionKey key = 
            (SelectionKey)readyItor.next();

          // Remove current entry
          readyItor.remove();

          // Get channel
          SocketChannel keyChannel = 
            (SocketChannel)key.channel();

          if (key.isConnectable()) {

            // Finish connection
            if (keyChannel.isConnectionPending()) {
              keyChannel.finishConnect();
            }

            // Send request
            String request = 
                 "GET / /n/r/n/r";
            keyChannel.write(encoder.encode(
              CharBuffer.wrap(request)));

          } else if (key.isReadable()) {

            // Read what's ready in response
            keyChannel.read(buffer);
            buffer.flip();

            // Decode buffer
            decoder.decode(buffer, 
              charBuffer, false);

            // Display
            charBuffer.flip();
            System.out.print(charBuffer);

            // Clear for next pass
            buffer.clear();
            charBuffer.clear();

          } else {
            System.err.println("Ooops");
          }
        }
      }
    } catch (UnknownHostException e) {
      System.err.println(e);
    } catch (IOException e) {
      System.err.println(e);
    } finally {
      if (channel != null) {
        try {
          channel.close();
        } catch (IOException ignored) {
        }
      }
    }
    System.out.println();
  }
}

Non-Blocking Servers

The final piece is having a Web server use the NIO package. With the new I/O capabilities, you can create a Web server that does not require one thread per connection. You can certainly pool threads for long processing tasks, but all you have to do is select and wait for something to do, not have all the threads waiting separately.

The basic setup of the server using channels involves you calling bind to connect a ServerSocketChannel to a InetSocketAddress.

ServerSocketChannel channel = 
  ServerSocketChannel.open();
channel.configureBlocking(false);
InetSocketAddress isa = 
  new InetSocketAddress(port);
channel.socket().bind(isa);

Everything else is the same as the client reading, except this time you need to register the OP_ACCEPT key, and check for isAcceptable when the selector notifies you of the event. It is that simple.

The following code example shows just how simple this is. It is your basic single-threaded server, sending back a canned text message for each request. Just use telnet to connect to port 9999 and see the response.

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;

public class Server {
  private static int port = 9999;
  public static void main(String args[]) 
      throws Exception {
    Selector selector = Selector.open();

    ServerSocketChannel channel = 
      ServerSocketChannel.open();
    channel.configureBlocking(false);
    InetSocketAddress isa = 
      new InetSocketAddress(port);
    channel.socket().bind(isa);

    // Register interest in when connection
    channel.register(selector, 
      SelectionKey.OP_ACCEPT);

    // Wait for something of interest to happen
    while (selector.select() > 0) {
      // Get set of ready objects
      Set readyKeys = selector.selectedKeys();
      Iterator readyItor = readyKeys.iterator();

      // Walk through set
      while (readyItor.hasNext()) {

        // Get key from set
        SelectionKey key = 
          (SelectionKey)readyItor.next();

        // Remove current entry
        readyItor.remove();

        if (key.isAcceptable()) {
          // Get channel
          ServerSocketChannel keyChannel = 
            (ServerSocketChannel)key.channel();

          // Accept request
          Socket socket = keyChannel.accept();

          // Return canned message
          PrintWriter out = new PrintWriter(
            socket.getOutputStream(), true);
          out.println("Hello, NIO");
          out.close();
        } else {
          System.err.println("Ooops");
        }
      }
    }
    // Never ends
  }
}

After accepting the request, you could get the channel from the socket, make it non-blocking, and register that with the selector, too. This framework just provides the basics of using the NIO classes within a Web server. For additional information about creating a multi-threaded server, see the JavaWorld article referenced in the Resources section.

Conclusion

The New I/O features introduced to the J2SE version 1.4 Beta release provide exciting new ways to improve the performance of your programs. By taking advantage of the new capabilities, not only will they be faster but they can be much more scalable because you won't have to worry about tasks like one thread per connection. This is especially important on the server side, greatly increasing the possible number of simultaneous connections supported.

Note: If you look at the list of capabilities in JSR 51, you'll notice there is mention of scanning and formatting support, similar to C's printf. This feature didn't make the 1.4 beta release and will be saved for a later version.

 

企业数字化转型AI大模型赋能智能体平台及AI场景应用规划方案(生态合作版).pptx 立即下载

相关推荐

智慧环保生态保护行业可信数据空间应用规划方案(技术方案版).pptx

智慧环保生态保护行业可信数据空间应用规划方案(技术方案版).pptx

New I/0 Functionality for JavaTM 2 Standard Edition 1.4 (转)

New I/0 Functionality for JavaTM 2 Standard Edition 1.4 (转)[@more@]New I/0 Functionality for JavaTM 2 Standard Edi...

csd3176的博客 119

MCGS的Http协议驱动,支持http协议

硬件配置 参数设置 设备属性 设备命令 通讯状态 附录 #HTTP 1、 设备简介 驱动类型 该驱动为独立设备,直接添加构件即可,不需要挂载到父设备下 通讯协议 采用标准HTTP1.1协议 通讯方式 驱动构件为客户端。 2、 硬件连接 本软件在通讯之前,请保证通讯连接正确。通讯连接方式:采用标准的RJ45接口的以太网接线(对调网线或使用HUB交换)。 3、 设备通讯参数 本设备为独立设备,无父设备参数 4、 设备构件参数设置 “HTTP设备”参数设置如下: <1> 内部属性: 构建url信息。 <2> 最小采集周期:本软件对设备进行操作的时间周期,单位为ms,默认为100ms。 <3> 通讯等待时间:通讯数据接收等待时间,默认设置为200ms,当采集速度要求较高或数据量较大时,设置值可适当减小或增大。 <4> HttpHead:http head添加需要的字段,不需要添加http head时值为空,默认不添加。 5、 设备命令 本设备构件提供设备命令,用于进行相应的操作,设备命令的格式如下: 设备命令 命令介绍 GetHttpHead 格式1 GetHttpHead(headStr) 用途 获取http head参数 参数 headStr 参数可以为字符型变量、字符串常量 例1 !SetDevice(设备0,6,"GetHttpHead(headStr)") 获取http head数据保存到headStr中 SetHttpHead 格式1 SetHttpHead(headStr) 用途 设置http head参数 参数 headStr 参数可以为字符型变量、字符串常量

The Science of JavaTM Sound Technology

  The Science of JavaTM Sound TechnologyBy Michael D. Meloan(June 1999) Sound creates mood, triggers memories, and in conjunction with visual imagery weaves whole worlds of fantasy. Sound is t

CanFly的专栏 2653

【分享】获取微信通讯录python代码形式实现

微信号”, “昵称”, “地区”, “备注”, “标签”, “签名”, “来源”5. 找到最后一个空格所在的位置(后一个就是真正的联系人了)当前微信号与上一个相同的时候,说明到底部了,可以跳出循环。3. 滚动鼠标到最顶部(防止已经滚动了一部分了)7.记录下上一个联系人的微信号。7. 无限循环按键盘下箭头。获取详情中的以下元素内容。6. 点击第一个联系人。4. 获取联系人列表。

程序员老狼专注开发aigc或客服系统应用 2895

攻克JESD204B多ADC同步:从时钟对齐到数据对齐的实战解析

本文深入解析了JESD204B多ADC同步的系统性挑战与实战解决方案。从确保设备时钟同源、精确捕获SYSREF信号,到管理接收端弹性缓冲区与释放点,文章提供了从时钟对齐到数据对齐的完整调试路径与排查清单,是攻克高速数据采集系统中多片ADC同步难题的实用指南。

weixin_29231725的博客 199

jar-The Java Archive Tool

jar-The Java Archive ToolCombines multiple files into a single JAR archive file. SYNOPSISjar [ options ] [manifest] destination input-file [input-files]DESCRIPTIONThe jar tool is a java

CanFly的专栏 1786

grafana使用方法

1、点击仪表盘2、新建仪表盘3、选择数据源4、选择查询的条件5、美化。

2403_87359664的博客 327

Compressing and Decompressing Data using JavaTM APIs

Compressing and Decompressing Data using JavaTM APIsby Qusay H. Mahmoud with contributions from Konstantin KladkoFebruary 2002 Many sources of information contain redundant data or data that adds

CanFly的专栏 1733

西门子 S7-200 SMART 系列六:手把手教你配置S7-200 SMART Modbus RTU

最新发表:https://www.ics-pedia.com/%e8%a5%bf%e9%97%a8%e5%ad%90-s7-200-smart-%e7%b3%bb%e5%88%97%e5%85%ad%ef%bc%9a%e6%89%8b%e6%8a%8a%e6%89%8b%e6%95%99%e4%bd%a0%e9%85%8d%e7%bd%aes7-200-smart-modbus-rtu%e5%ae%9e%e4%be%8b/

John_09040211的博客 3283

STM32+A4988控制步进电机

基于A4988芯片驱动42步进电机,在STM32F1上进行测试,最高可以实现16细分。

个人博客 4万+

What's New in the JMF 2.0 Reference Implementations

   Whats New in the JMF 2.0 Reference Implementations New Features in JMF 2.1.1 FCS Improved RTP API Added support for H.263/1998 (RFC 2429) - now can interoperate with Darwin based RTSP

CanFly的专栏 1639

使用mindie:2.0.RC2-800I-A2-py311-openeuler24.03-lts制作一个通用的模型推理性能测试的镜像

本文详细介绍了在NPU环境下进行模型推理性能测试的完整流程。首先配置了测试所需的环境和设备信息,包括Python 3.10.9和3.11.6版本、测试脚本和镜像文件。然后分步骤说明了镜像制作过程:创建特权容器、安装Python 3.10.9、配置VLLM环境,并详细描述了测试容器的启动方法。最后提供了镜像打包和使用指南,包括如何加载镜像、启动容器、运行测试脚本(以DeepSeek-32B模型为例)以及更换测试模型的步骤。整个过程涉及环境变量配置、权限设置和服务启动等关键操作。

m0_50105717的博客 1015

Drag and Drop: New Data Transfer Capabilities in the JavaTM 2 Platform, Standard Edition (J2SETM), version 1.4

New Data Transfer CapabilitiesJohn ZukowskiNovember 2001 Sun is currently undergoing their third beta release of the JavaTM 2 Platform, Standard Edition (J2SETM), version 1.4. This latest release

CanFly的专栏 1582

SLAM Cartographer(18)后端优化问题求解器

了解经过闭环检测构建了子图与节点之间的约束之后,通过后端优化求解器进行优化求解。核心是基于Ceres库进行SPA(Sparse Pose Adjustment)的优化方法,把后端优化问题描述成为一个最小二乘的问题求解

氢键H-H 5685

QProgressBar:常用接口、样式表及自定义进度条实现

在Qt开发中,QProgressBar 是一个非常常用的控件,用于显示任务的进度。无论是文件下载、数据处理还是其他耗时操作,QProgressBar 都能直观地展示当前进度。本文将详细介绍QProgressBar 的使用方法,包括常用接口、样式表设置,并额外补充一个自定义进度条的C++实现。

u011186532的专栏 1015

Distributed Java Programming with RMI and CORBA

Distributed Java Programming with RMI and CORBAQusay H. MahmoudJanuary 2002 The Java Remote Method Invocation (RMI) mechanism and the Common Object Request Broker Architecture (CORBA) are the two

CanFly的专栏 1464

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

JINI NETWORK TECHNOLOGY DEFENDS THE ENVIRONMENT

JINITM NETWORK TECHNOLOGY DEFENDS THE ENVIRONMENT by Jon Byous November 8, 2001 -- Scientists at the U.S. Department of Energys Pacific Northwest National Laboratory (PNNL), in Richland,

CanFly的专栏 1335

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

NLEASHING J2EETM TECHNOLOGY'S POWER WITH EJBTM COMPONENTS

NLEASHING J2EETM TECHNOLOGYS POWER WITH EJBTM COMPONENTS by Michael Meloan March 20, 2001 -- The benefits of building ecommerce software applications from pretested, server-side JavaTM c

CanFly的专栏 1305

Understanding the Manifest

Understanding the Manifest JAR files can support a wide range of functionality, including electronic signing, version control, package sealing, extensions, and others. What gives JAR files the abi

CanFly的专栏 1271

Lightweight UI Framework(有產生圓形Button的源碼)

Java AWT: Lightweight UI FrameworkThe ProblemOne of the issues with the 1.0 AWT is that creating new components requires creating subclasses of java.awt.Canvas or java.awt.Panel, which means that

CanFly的专栏 1251

GENERATING INTEGER RANDOM NUMBERS(幾種產生隨機數方法的效率分析)

GENERATING INTEGER RANDOM NUMBERSThere are many ways to generate random numbers with the base libraries found in the Java 2 SDK, Standard Edition. If you havent kept up to date with changes to the

CanFly的专栏 1246

CREATING ROUND SWING BUTTONS 2

CREATING ROUND SWING BUTTONSThis tip is about round Swing buttons. Actually, the information inthis tip applies to a button of any arbitrary shape but to keep thediscussion simple, were just going to

CanFly的专栏 1193

Adding Undo and Redo to a Text Component

 These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms Adding Undo and Redo to a Text Component JTextArea textarea = new JTextArea(); final UndoManager

CanFly的专栏 1167

Getting Listeners from JavaBeansTM

Getting Listeners from JavaBeansTM An Amendment to the JavaBeans Specification Hans Muller and Mark DavidsonPresently all of the state in an AWT component that can be written can also be read, e.g

CanFly的专栏 1155
上一篇: CREATING ROUND SWING BUTTONS 2
下一篇: JINI NETWORK TECHNOLOGY DEFENDS THE ENVIRONMENT
CanFly
博客等级 码龄25年 0粉丝 18原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值