- Converting a text file to a CSV file
- Convert TXT to CSV in Java
- TXT to CSV Converter – Java API Installation#
- Convert TXT to CSV File in Java#
- Get a Free License#
- Conclusion#
- See Also#
- Convert TXT to CSV in Java
- TXT to CSV conversion with a few lines of Java code
- GroupDocs.Conversion
- About GroupDocs.Conversion for Java API
- Steps to Convert TXT to CSV in Java
- System Requirements
- TXT to CSV Live Demo
- Other supported TXT conversions in Java
- maderaka / Convert.java
- Преобразование TXT в CSV via Java
- Преобразование TXT в CSV Java для преобразования одной или нескольких страниц в CSV с использованием локальной библиотеки Java.
- Aspose.Cells for Java
- Overview
- Преобразование TXT в CSV с помощью Java
- Репозиторий
- Зависимость
- Сохраните TXT в CSV в Java онлайн бесплатно
Converting a text file to a CSV file
Since you are using Java 8 it is good to use the great streaming methods it give you. You can write your code simply like the following:
public static void main(String[] args) < String fileName = "./a.txt"; try (Streamstream = Files.lines(Paths.get(fileName))) < String result = stream.map(s ->s.split("\\s+")) .map(s -> Arrays.stream(s).collect(Collectors.joining(","))+"\n") .collect(Collectors.joining()); System.out.println(result); > catch (IOException e)
The final result is stored in result and you just need simply to write it into the file!
\$\begingroup\$ Thanks Guys, all these answers have helped me gain more understanding, wasn’t aware of a number of features that have been suggested. thanks for the advice. 🙂 \$\endgroup\$
\$\begingroup\$ Pooya, If I needed to remove the first «,» off each line much like: line = line.startsWith(«,») ? line.substring(1) : line; how would you suggest to put it into the stream.map command. \$\endgroup\$
\$\begingroup\$ @Graham: in the second map statement you can put your logic although it may look bit more complicated and probably cannot fit in single lambda expression \$\endgroup\$
If your input is already separated correctly by spaces, it seems all you need to do is to convert those into commas and you’re good. I’m not sure you need to go to/from arrays.
I would replace the code inside the loop:
Oh, and check for the array size like someone else mentioned.
\$\begingroup\$ Come to think of it, you could probably consolidate the 2 replace lines also: \$\endgroup\$
\$\begingroup\$ I like the combination of triming and replacing here, thanks for the tips 🙂 \$\endgroup\$
Question: is there a better, more efficent, way of doing this.
At what point do you call Scanner.close() ? When you’re dealing with input streams, you’re supposed to close them when you’re done.
For this reason, I’m not crazy about breaking OpenFile into a separate method. at least not in that way.
It’s good to break big chunks of logic into smaller, more manageable bits, but try something like this approach instead.
public Scanner openFile(String fileName) < try < return new Scanner(new File(fileName)); >catch (Exception e) < throw new IllegalArgumentException("Specified file doesn't exist: " + fileName); >>
But as far as closing your streams — I like try with resources.
try (Scanner scanner = openFile(filename)) < // do your stuff. >
Convert TXT to CSV in Java
TXT files can sometimes contain numeric data that you might need to process with some application. Accordingly, TXT to CSV file conversion can be helpful to parse the numeric data as comma separated values. This article covers how to convert a TXT file to CSV format programmatically in Java
TXT to CSV Converter – Java API Installation#
Aspose.Cells for Java supports working with different Excel file formats to create or manipulate the data in Java applications. You can easily configure the API by downloading the JAR files from the New Releases page or from the Aspose Repository by using the following Maven configurations.
AsposeJavaAPI Aspose Java API https://repository.aspose.com/repo/
com.aspose aspose-cells 22.6
Convert TXT to CSV File in Java#
You can convert a TXT file to CSV format in Java by following the steps below:
- Create an object of TxtLoadOptions class.
- Load the input file using a Workbook class object.
- Save the output CSV file at specified path.
The following code snippet demonstrates how to convert a TXT file to a CSV file programmatically in Java:
Get a Free License#
You may test all the features of the API without any evaluation limitations. Simply request a free temporary license to evaluate the API in its full capacity.
Conclusion#
In this article, you have learned how to convert TXT to CSV Comma Separated Values programmatically in Java. Such comma separated files are sometimes required by different workflows in order to parse or extract some useful information out of the numeric data. Moreover, you may take a look at the API documentation to check out several other features of the API. In case you need to communicate any of your concerns or ambiguities, please feel free to write to us at the forum.
See Also#
Convert TXT to CSV in Java
TXT to CSV conversion with a few lines of Java code
GroupDocs.Conversion
About GroupDocs.Conversion for Java API
GroupDocs.Conversion for Java is an advanced file format conversion API for converting between popular image and document formats such as Microsoft Office, OpenDocument, PDF, HTML, email, CAD. and much more with just a few lines of code. The native API automatically detects the formats of the original documents and offers many options for customizing the converted documents. Along with the function of extracting information from a document, it also supports caching of the conversion results to the local disk by default. However, any type of cache storage can be supported by implementing the appropriate interfaces — Amazon S3, Dropbox, Google Drive, Windows Azure, Reddis, or any others.
Convert your TXT files to CSV files in Java. It only takes a couple of lines of Java code on any platform of your choice, such as Windows, Linux, macOS. You can try converting TXT to CSV for free and evaluate the quality of the conversion results. Along with simple file conversion scripts, you can try more sophisticated options for loading the TXT source file and storing the CSV output.
For example, for the source file TXT, you can use the following upload options:
- automatic detection of the file format;
- specify a password for protected files (if the file format supports it);
- replace missing fonts to preserve the appearance of the document.
There are also advanced conversion options for the CSV file:
- convert a specific page of a document or a range of pages;
- add a watermark to the converted CSV.
Once the conversion is complete, you can save the CSV file to your local file path or to any third party storage such as FTP, Amazon S3, Google Drive, Dropbox etc. Please note — to convert TXT to CSV, you do not need to install any additional software, such as MS Office, Open Office, Adobe Acrobat Reader etc.
Steps to Convert TXT to CSV in Java
GroupDocs.Conversion allows developers to easily convert a TXT file to CSV with a few lines of code.
- Create a new instance of the Converter class and upload the file TXT with the full path
- Set ConvertOptions for document type to CSV.
- Call the convert() method and pass the document name (full path) and format (CSV) as a parameter
System Requirements
Basic conversion using GroupDocs.Conversion for the Java API can be done with just a few lines of code. Our APIs are supported on all major platforms and operating systems. Before executing the code below, make sure you have the following prerequisites installed on your system.
- Operating systems: Microsoft Windows, Linux, MacOS
- Development environment: NetBeans, Intellij IDEA, Eclipse, etc.
- Java runtime: J2SE 6.0 and above
- Get the latest GroupDocs.Conversion for Java from Maven
// Load source file TXT for conversion Converter converter = new Converter("input.txt"); // Prepare conversion options for target format CSV ConvertOptions convertOptions = new FileType().fromExtension("csv").getConvertOptions(); // Convert to CSV format converter.convert("output.csv", convertOptions);
TXT to CSV Live Demo
Convert TXT to CSV now by visiting the GroupDocs.Conversion App website. The free demo has the following benefits
No need to write any code
Just upload the source file
Get download link to save the file
Other supported TXT conversions in Java
You can also convert TXT to many other file formats. Please see the list below.
(Microsoft Word Binary Format)
(Microsoft Word 2007 Marco File)
(Office 2007+ Word Document)
(Microsoft Word Template Files)
(Microsoft Word 2007+ Template File)
(Microsoft Word Template File )
(Graphical Interchange Format)
(Joint Photographic Expert Group Image)
(OpenDocument Text File Format)
(OpenDocument Standard Format)
maderaka / Convert.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java . io .*; |
public class Convert |
public static void main ( String [] args ) |
System . out . println ( «Initialize . » ); |
Read read = new Read ( «soal01.txt» ); |
Print print = new Print (); |
for ( int i = 1 ; i <= 3 ; i ++) |
try |
print . setFileName ( «jawaban» + i + «.csv» ); |
read . setPrint ( print ); |
read . exec ( i ); |
> catch ( IOException ex ) |
ex . printStackTrace (); |
> |
> |
System . out . println ( «Finished» ); |
> |
> |
class Print |
protected String fileName ; |
protected FileWriter writer ; |
public Print () <> |
public Print ( String fileName ) throws IOException |
this . fileName = fileName ; |
this . writer = new FileWriter ( this . fileName ); |
> |
public String getFileName () |
return this . fileName ; |
> |
public void setFileName ( String fileName ) throws IOException |
this . fileName = fileName ; |
this . writer = new FileWriter ( this . fileName ); |
> |
public void close () throws IOException |
this . writer . flush (); |
this . writer . close (); |
> |
public void addRow ( String [] c ) throws IOException |
int l = c . length ; |
for ( int i = 0 ; i < l ; i ++) |
this . writer . append ( c [ i ]); |
if ( i != ( l — 1 )) |
this . writer . append ( «,» ); |
> |
> |
this . writer . append ( ‘\n’ ); |
> |
> |
class Read |
protected String fileName ; |
protected BufferedReader bufferedReader ; |
protected Print print ; |
public Read ( String fileName ) |
this . fileName = fileName ; |
> |
public Read ( Print print , String fileName ) |
this . print = print ; |
this . fileName = fileName ; |
> |
public void setPrint ( Print print ) |
this . print = print ; |
> |
public Print getPrint () |
return this . print ; |
> |
public void exec ( Integer type ) |
String sCurrentLine = «» ; |
try |
this . bufferedReader = new BufferedReader ( |
new FileReader ( this . fileName )); |
while (( sCurrentLine = this . bufferedReader . readLine ()) != null ) |
String [] columns = sCurrentLine . split ( » \t » ); |
int length = columns . length ; |
if ( type == 1 ) |
this . print . addRow ( columns ); |
> else if ( length >= 2 ) |
double col1 = Double . parseDouble ( columns [ 1 ]); |
if ( col1 > 20 ) |
if ( type == 2 ) |
this . print . addRow ( columns ); |
> else if ( type == 3 && length >= 3 && columns [ 2 ] != null ) |
this . print . addRow ( columns ); |
> |
> |
> |
> |
this . print . close (); |
> catch ( IOException ex ) |
ex . printStackTrace (); |
> finally |
try |
if ( this . bufferedReader != null ) |
this . bufferedReader . close (); |
> |
> catch ( IOException ex ) |
ex . printStackTrace (); |
> |
> |
> |
> |
Преобразование TXT в CSV via Java
Преобразование TXT в CSV Java для преобразования одной или нескольких страниц в CSV с использованием локальной библиотеки Java.
Aspose.Cells for Java
Overview
Download from Maven
You can easily use Aspose.Cells for Java directly from a Maven based project by following simple installation instructions.
Преобразование TXT в CSV с помощью Java
Как преобразовать TXT в CSV? С помощью библиотеки Aspose.Cells for Java вы можете легко программно преобразовать TXT в CSV с помощью нескольких строк кода. Aspose.Cells for Java способен создавать кроссплатформенные приложения с возможностью создания, изменения, преобразования, рендеринга и печати всех файлов Excel. Java Excel API не только конвертирует форматы электронных таблиц, но также может отображать файлы Excel в виде изображений, PDF, HTML, ODS, CSV, SVG, JSON, WORD, PPT и т. д., что делает его идеальным выбором для обмена документы в отраслевом стандарте форматы. Вы можете скачать его последнюю версию прямо с Maven и установите его в своем проекте на основе Maven, добавив следующие конфигурации в файл pom.xml.
Репозиторий
AsposeJavaAPI Aspose Java API https://repository.aspose.com/repo/
Зависимость
com.aspose aspose-cells version of aspose-cells API jdk17
Сохраните TXT в CSV в Java онлайн бесплатно
В следующем примере показано, как преобразовать TXT в CSV в Java.
Следуйте простым шагам, чтобы преобразовать TXT в CSV. Загрузите файл TXT, а затем просто сохраните его как файл CSV. Как для чтения TXT, так и для записи CSV вы можете использовать полные имена файлов. Содержимое и форматирование вывода CSV будут идентичны исходному документу TXT.