Home Java javaTutorial How to use Java to convert GBK project to uft8 method sharing

How to use Java to convert GBK project to uft8 method sharing

Aug 13, 2017 am 09:34 AM
java project

This article mainly introduces the method examples of converting GBK projects to uft8 using Java. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

This article introduces how to use java to convert GBK projects to uft8 and share it with everyone. The details are as follows:

The default encoding under windows is GBK and gb2312. How to convert gbk's java project to utf8? If you modify the project encoding directly, the Chinese characters in the java files inside will actually be garbled. I wrote a program for batch conversion of java projects for fun.

Why transcode?

Some old projects, or friends’ projects, didn’t notice before that they were not UTF8 on Windows, and if you need to read comments or something, you can’t change the encoding attributes one file at a time.

The trial scope of this program

gbk code or gb2312 project can be converted

The idea of ​​coding conversion

Originally I wanted to make a universal program that can automatically detect encoding and convert automatically. However, due to the inaccurate judgment of the encoding type, conversion to GBK was made.

  1. Specify gbk encoding to read the file stream, load it into memory, and convert it to String type content

  2. Convert String content to utf8 String

  3. Write String content to file

Core code:


public class TransferProject{
  public static void transferFile(String pathName,intdepth)throwsException{
    File dirFile = new File(pathName);
    if (!isValidFile(dirFile)) return;
    //获取此目录下的所有文件名与目录名
    String[] fileList = dirFile.list();
    int currentDepth = depth + 1;
    for (int i = 0; i < fileList.length; i++) {
      String string = fileList[i];
      File file = new File(dirFile.getPath(), string);
      String name = file.getName();
      //如果是一个目录,搜索深度depth++,输出目录名后,进行递归
      if (file.isDirectory()) {
        //递归
        transferFile(file.getCanonicalPath(), currentDepth);
      } else {
        if (name.contains(".java") || name.contains(".properties") || name.contains(".xml")) {
          readAndWrite(file);
          System.out.println(name + " has converted to utf8 ");
        }
      }
    }
  }

 
  private static boolean isValidFile(File dirFile)throwsIOException{
    if (dirFile.exists()) {
      System.out.println("file exist");
      return true;
    }
    if (dirFile.isDirectory()) {
      if (dirFile.isFile()) {
        System.out.println(dirFile.getCanonicalFile());
      }
      return true;
    }
    return false;
  }

  private static void readAndWrite(File file)throwsException{
    String content = FileUtils.readFileByEncode(file.getPath(), "GBK");
    FileUtils.writeByBufferedReader(file.getPath(), new String(content.getBytes("UTF-8"), "UTF-8"));
  }

  public static void main(String[] args)throwsException{
    //程序入口,制定src的path
    String path = "/Users/mac/Downloads/unit06_jdbc/src";
    transferFile(path, 1);
  }
}
Copy after login


public class FileUtils{
  public static void writeByBufferedReader(String path, String content){
    try {
      File file = new File(path);
      file.delete();
      if (!file.exists()) {
        file.createNewFile();
      }

      FileWriter fw = new FileWriter(file, false);
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(content);
      bw.flush();
      bw.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public staticStringreadFileByEncode(String path, String chatSet)throwsException{
    InputStream input = new FileInputStream(path);
    InputStreamReader in = new InputStreamReader(input, chatSet);
    BufferedReader reader = new BufferedReader(in);
    StringBuffer sb = new StringBuffer();
    String line = reader.readLine();
    while (line != null) {
      sb.append(line);
      sb.append("\r\n");
      line = reader.readLine();
    }
    return sb.toString();
  }
}
Copy after login

The above is the detailed content of How to use Java to convert GBK project to uft8 method sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

New work from the author of Mamba: Distilling Llama3 into a hybrid linear RNN New work from the author of Mamba: Distilling Llama3 into a hybrid linear RNN Sep 02, 2024 pm 01:41 PM

The key to Transformer's great success in the field of deep learning is the attention mechanism. The attention mechanism allows the Transformer-based model to focus on the parts related to the input sequence, achieving better context understanding. However, the disadvantage of the attention mechanism is that the computational overhead is high, which will increase quadratically with the input size, making it difficult for the Transformer to handle very long texts. Some time ago, the emergence of Mamba broke this situation, and it can achieve linear expansion as the context length increases. With the release of Mamba, these state space models (SSM) can match or even surpass Transformer at small and medium scales while maintaining order.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Interpretation of KDD2024 Best Student Paper, University of Science and Technology of China, Huawei Noah: New Paradigm of Sequence Recommendation DR4SR Interpretation of KDD2024 Best Student Paper, University of Science and Technology of China, Huawei Noah: New Paradigm of Sequence Recommendation DR4SR Sep 02, 2024 pm 03:07 PM

The AIxiv column is a column where this site publishes academic and technical content. In the past few years, the AIxiv column of this site has received more than 2,000 reports, covering top laboratories from major universities and companies around the world, effectively promoting academic exchanges and dissemination. If you have excellent work that you want to share, please feel free to contribute or contact us for reporting. Submission email: liyazhou@jiqizhixin.com; zhaoyunfeng@jiqizhixin.com This work was completed by the IEEE Fellow Chen Enhong team of the National Key Laboratory of Cognitive Intelligence and Huawei's Noah's Ark Laboratory. Professor Chen Enhong’s team is deeply involved in the fields of data mining and machine learning, and has published many papers in top journals and conferences, and has been cited in Google Scholar papers.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles