2024-08-12

Java IO流是Java进行数据输入输出操作的重要部分,以下是一些常见的IO流知识点及其简单解释和示例代码:

  1. 字节流

    • InputStreamOutputStream
    • 示例代码:

      
      
      
      InputStream is = new FileInputStream("file.txt");
      int byteContent;
      while ((byteContent = is.read()) != -1) {
          // 处理读取的字节
      }
      is.close();
       
      OutputStream os = new FileOutputStream("file.txt");
      String content = "Hello, World!";
      os.write(content.getBytes());
      os.close();
  2. 字符流

    • ReaderWriter
    • 示例代码:

      
      
      
      Reader reader = new FileReader("file.txt");
      int charContent;
      while ((charContent = reader.read()) != -1) {
          // 处理读取的字符
      }
      reader.close();
       
      Writer writer = new FileWriter("file.txt");
      String content = "Hello, World!";
      writer.write(content);
      writer.close();
  3. 缓冲流

    • BufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriter
    • 示例代码:

      
      
      
      BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
      String line;
      while ((line = reader.readLine()) != null) {
          // 处理读取的行
      }
      reader.close();
       
      BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
      writer.write("Hello, World!");
      writer.close();
  4. 对象流

    • ObjectInputStreamObjectOutputStream
    • 示例代码:

      
      
      
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
      oos.writeObject(new MyClass());
      oos.close();
       
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));
      MyClass myObject = (MyClass) ois.readObject();
      ois.close();
  5. 标准输入输出流

    • System.inSystem.outSystem.err
    • 示例代码:

      
      
      
      Scanner scanner = new Scanner(System.in);
      System.out.println("请输入内容:");
      String content = scanner.nextLine();
      System.out.println("您输入的内容是:" + content);
      scanner.close();
  6. 文件流

    • FileInputStreamFileOutputStreamFileReaderFileWriter
    • 示例代码已在字节流和字符流部分给出。
  7. 数据流

    • DataInputStreamDataOutputStream
    • 示例代码:

      
      
      
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
      dos.writeDouble(123.456);
      dos.writeInt(789);
      dos.close();
2024-08-12

在Kotlin中,有许多经典的书籍可以学习,以下是一些推荐的书籍:

  1. 《Kotlin Programming: The Big Nerd Ranch Guide》

这本书由Big Nerd Ranch提供,涵盖了Kotlin的基础知识,包括语言特性、集合、函数式编程等。

  1. 《Kotlin in Action》

这本书由Raoul-Gabriel Urma和Alan Mycroft撰写,涵盖了Kotlin的基础知识,并提供了一些实际的例子。

  1. 《Kotlin for Android Developers》

这本书由Joshua Bloch和Google的开发者撰写,涵盖了如何使用Kotlin进行Android开发。

  1. 《Practical Kotlin》

这本书由JetBrains的专家撰写,涵盖了Kotlin的主要特性,并提供了实际的代码示例。

  1. 《Kotlin for Java Developers》

这本书由JetBrains的专家撰写,涵盖了Java开发者如何迁移到Kotlin。

  1. 《Kotlin Reference》

这本书由JetBrains提供,是Kotlin语言的官方参考,涵盖了语言的所有特性。

  1. 《Kotlin Programming: Next-Generation Language》

这本书由Packt Publishing提供,涵盖了Kotlin的基础知识,并提供了一些实际的例子。

选择哪本书取决于你的具体需求和你当前的编程水平。如果你是一位Java开发者,可能会更倾向于选择能帮助你迁移到Kotlin的书籍。如果你是编程初学者,可能会更倾向于选择从基础开始教学的书籍。

2024-08-12

java.lang.ClassNotFoundException异常通常发生在Java环境中,当应用程序尝试加载某个类但无法找到指定的类时抛出。常见原因包括类路径(classpath)设置不正确,或者尝试加载的类根本就不存在。

解决方法:

  1. 确认类名是否拼写正确,包括大小写。
  2. 确认需要加载的类文件是否已经被编译,并且.class文件存在于classpath中。
  3. 检查项目的构建路径,确保编译后的.class文件被包含在classpath中。
  4. 如果是在IDE中工作,确保项目的构建路径设置正确,且所有依赖库都已经被正确加载。
  5. 如果是在运行打包后的JAR文件,确保所有必要的类文件都包含在JAR中,并且在运行时指定了正确的classpath。
  6. 如果类是通过网络加载或者其他方式动态加载的,确保相关资源的URL或路径是正确的。

示例:如果你在运行时遇到这个异常,并且确认类文件存在,可以尝试以下命令来设置classpath:




java -cp .;lib/* your.package.YourClass

这里-cp .;lib/*表示当前目录和lib子目录下的所有jar文件都会被加入到classpath中去查找类文件。

2024-08-12

Java对接第三方接口通常涉及到发送HTTP请求。以下是三种常见的方式:

  1. 使用Java内置的HttpURLConnection类。
  2. 使用Apache的HttpClient库。
  3. 使用现代的OkHttp库。

以下是每种方式的示例代码:

  1. 使用HttpURLConnection



URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
 
// 写入请求体
OutputStream os = conn.getOutputStream();
os.write("key1=value1&key2=value2".getBytes());
os.close();
 
// 读取响应
InputStream is = conn.getInputStream();
// 处理响应...
is.close();
  1. 使用Apache的HttpClient



HttpPost post = new HttpPost("http://example.com/api");
post.setEntity(new UrlEncodedFormEntity(Arrays.asList(
    new BasicNameValuePair("key1", "value1"),
    new BasicNameValuePair("key2", "value2"))));
 
HttpResponse response = HttpClients.createDefault().execute(post);
// 处理响应...
  1. 使用OkHttp:



OkHttpClient client = new OkHttpClient();
 
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "key1=value1&key2=value2");
Request request = new Request.Builder()
  .url("http://example.com/api")
  .post(body)
  .build();
 
Response response = client.newCall(request).execute();
// 处理响应...

每种方式都适用于不同的场景,选择哪种方式取决于你的项目需求和个人喜好。HttpURLConnection是Java标准库的一部分,而HttpClientOkHttp则是第三方库。OkHttp是目前最快的HTTP客户端之一,而HttpClient由Apache维护,提供了更多的功能和灵活性。

2024-08-12

在Java中,判断一个对象是否为空(null),可以直接使用等式比较操作符(==)。以下是一个简单的示例代码:




public class Main {
    public static void main(String[] args) {
        Object obj = null;
 
        // 判断obj是否为空
        if (obj == null) {
            System.out.println("对象是空的");
        } else {
            System.out.println("对象不是空的");
        }
    }
}

如果你想要检查一个对象是否是Java中的空对象(例如一个空的String、空的数组等),可以使用相应的方法,例如String.isEmpty()Array.length == 0等。




public class Main {
    public static void main(String[] args) {
        String str = "";
        int[] arr = new int[0];
 
        // 判断str是否为空字符串
        if (str.isEmpty()) {
            System.out.println("字符串是空的");
        }
 
        // 判断arr是否为空数组
        if (arr.length == 0) {
            System.out.println("数组是空的");
        }
    }
}

请根据实际情况选择合适的方法来判断空对象。

2024-08-12



// 使用Web Cryptography API进行非对称加密与解密
 
// 生成非对称密钥对
crypto.subtle.generateKey(
    {
        name: "RSA-OAEP",
        modulusLength: 2048,
        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
        hash: "SHA-256",
    },
    true,
    ["encrypt", "decrypt"]
)
.then(function(key) {
    // 获取公钥
    var publicKey = key.publicKey;
    // 获取私钥
    var privateKey = key.privateKey;
 
    // 使用公钥加密数据
    crypto.subtle.encrypt(
        {
            name: "RSA-OAEP",
            hash: "SHA-256"
        },
        publicKey,
        dataToEncrypt
    )
    .then(function(encryptedData) {
        // 处理加密后的数据
        console.log(encryptedData);
 
        // 使用私钥解密数据
        crypto.subtle.decrypt(
            {
                name: "RSA-OAEP",
                hash: "SHA-256"
            },
            privateKey,
            encryptedData
        )
        .then(function(decryptedData) {
            // 处理解密后的数据
            console.log(decryptedData);
        });
    });
});
 
// 使用CryptoJS进行AES密钥生成与加密解密
var dataToEncrypt = "需要加密的数据";
var aesKey = CryptoJS.lib.WordArray.random(128/8); // 生成128位的AES密钥
var encryptedData = CryptoJS.AES.encrypt(dataToEncrypt, aesKey);
var decryptedData = CryptoJS.AES.decrypt({ciphertext: CryptoJS.enc.Hex.parse(encryptedData.ciphertext)}, aesKey);
 
console.log(encryptedData.toString()); // 输出加密数据
console.log(decryptedData.toString(CryptoJS.enc.Utf8)); // 输出解密数据

这段代码展示了如何使用Web Cryptography API生成非对称密钥对并进行加密解密,以及如何使用CryptoJS库生成随机的AES密钥并对数据进行加密解密。这两种方法在安全性和性能上都有所不同,开发者可以根据实际需求选择合适的方法。

2024-08-12

以下是一个简单的示例,展示如何在Android中使用TabLayout和ViewPager2结合Fragment实现标签页切换的功能。

首先,在布局文件中添加TabLayout和ViewPager2:




<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
 
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/tabLayout"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>
 
</androidx.constraintlayout.widget.ConstraintLayout>

接下来,创建对应的Fragment类:




public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);
    }
}

然后,在Activity中设置TabLayout和ViewPager2:




public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        TabLayout tabLayout = findViewById(R.id.tabLayout);
        ViewPager2 viewPager = findViewById(R.id.viewPager);
 
        viewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                // Return a new instance of your fragment with the position
                return MyFragment.newInstance(position);
            }
 
            @Override
            public int getItemCount() {
                // Number of tabs/fragments
                return 2;
            }
        });
 
        // Set up the TabLayout with the ViewPager2
        new TabLayout
2024-08-12

在Java和JavaScript中实现WGS84坐标系与百度坐(BD09)坐标系、火星坐标系(GCJ02)的互转,可以使用开源库如proj4jol(OpenLayers库)。以下是使用proj4j库的示例代码。

首先,添加proj4j依赖到你的项目中。

Java 示例代码:




import org.osgeo.proj4j.CRSFactory;
import org.osgeo.proj4j.CoordinateReferenceSystem;
import org.osgeo.proj4j.CoordinateTransform;
import org.osgeo.proj4j.ProjCoordinate;
 
public class CoordinateConverter {
 
    public static void main(String[] args) {
        CRSFactory crsFactory = new CRSFactory();
 
        // 设置WGS84和GCJ02的坐标系
        CoordinateReferenceSystem wgs84 = crsFactory.createFromName("EPSG:4326");
        CoordinateReferenceSystem bd09 = crsFactory.createFromName("EPSG:3395");
        CoordinateReferenceSystem gcj02 = crsFactory.createFromName("EPSG:3455");
 
        // 创建转换对象
        CoordinateTransform transformToBaidu = new CoordinateTransform(wgs84, bd09);
        CoordinateTransform transformToGCJ02 = new CoordinateTransform(wgs84, gcj02);
 
        // 原始WGS84坐标点
        double lat = 40.0;
        double lon = 116.0;
 
        // 转换坐标
        ProjCoordinate coord = new ProjCoordinate(lon, lat);
        transformToBaidu.transform(coord, coord);
        System.out.println("Baidu Coordinate: " + coord.x + ", " + coord.y);
 
        transformToGCJ02.transform(coord, coord);
        System.out.println("GCJ02 Coordinate: " + coord.x + ", " + coord.y);
    }
}

JavaScript 示例代码(使用ol库):




import 'ol/ol.css';
import { transform } from 'ol/proj';
 
// 原始WGS84坐标点
const lat = 40.0;
const lon = 116.0;
 
// 百度坐标系转换
const bd09 = transform([lon, lat], 'EPSG:4326', 'EPSG:3395');
console.log('Baidu Coordinate:', bd09);
 
// 火星坐标系转换
const gcj02 = transform([lon, lat], 'EPSG:4326', 'EPSG:3455');
console.log('GCJ02 Coordinate:', gcj02);

请确保在Java中有对应的EPSG:3395和EPSG:3455的坐标系定义,如果没有,可能需要自定义或者使用其他方法实现。在JavaScript中,ol库通常内置了这些坐标系的定义,因此可以直接使用。

注意:这些代码示例仅用于说明如何进行坐标系转换,并不保证能够正确处理所有边界情况或特殊情况。在实际应用中,可能需要额外的错误处理和边界检查。

2024-08-12

在Java中,可以通过实现Comparator接口来创建一个自定义排序器。以下是一个简单的自定义排序器示例,它根据一个字符串数组中的字符串长度进行排序。




import java.util.Arrays;
import java.util.Comparator;
 
public class CustomSort {
    public static void main(String[] args) {
        String[] strings = {"apple", "banana", "cherry", "date"};
 
        // 使用自定义排序器根据字符串长度排序
        Arrays.sort(strings, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return Integer.compare(s1.length(), s2.length());
            }
        });
 
        // 输出排序后的数组
        System.out.println(Arrays.toString(strings));
    }
}

在这个例子中,我们创建了一个匿名内部类实现了Comparator接口,并覆盖了compare方法。在compare方法中,我们比较了两个字符串的长度,并使用Integer.compare方法来确保正确处理长度差值为Integer.MIN\_VALUE的情况。

运行这段代码会按照字符串长度升序排列数组。如果你想要降序排列,只需在compare方法中调换s1s2的位置即可。

2024-08-12

在Java中,当需要处理小数计算并保存到MySQL数据库时,应当使用DECIMAL类型来代替FLOATDOUBLE,因为DECIMAL可以提供更精确的小数处理。

以下是一个Java代码示例,演示如何使用PreparedStatement将小数保存到MySQL数据库的DECIMAL字段中:




import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
public class SaveDecimalToMySQL {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/databaseName";
        String user = "username";
        String password = "password";
 
        try (Connection conn = DriverManager.getConnection(url, user, password);
             PreparedStatement pstmt = conn.prepareStatement("INSERT INTO tableName (decimalColumn) VALUES (?)")) {
            
            // 设置小数值
            pstmt.setBigDecimal(1, BigDecimal.valueOf(123.456789));
            
            // 执行插入操作
            pstmt.executeUpdate();
            
            System.out.println("小数保存成功!");
            
        } catch (SQLException e) {
            System.out.println("数据库操作失败: " + e.getMessage());
        }
    }
}

在这个例子中,我们使用了BigDecimal.valueOf()来创建一个BigDecimal对象,这是为了确保精度是正确的。然后使用PreparedStatementsetBigDecimal()方法将其设置到SQL语句中对应的小数字段。

请确保在实际使用时替换databaseName, tableNamedecimalColumn为你的数据库名、表名和列名,以及替换usernamepassword为你的数据库登录凭据。