top of page

File Formatting | CIT Year 1 | 2018

Files that contain a series of floating point numbers that are very tough to read. This script process all the numbers in an original file and create a new file that is much easier to read.

The program gets the original file name (with or without path) from the user, specify's the output file name (with or without path), allow the user to set the field width and set the precision (after decimal point) and allow the user to set how many columns on each line (from 1 to 5). The new file is not created until the input file actually exist, the destination file does not exist (does not overwrite any file) and the field width and precision are specified as well as the number of columns is in the range of 1 to 5

 

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Scanner;

import javax.swing.JOptionPane;


/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

/**

*

* @author danielwevers

*/

public class fileFormatting extends javax.swing.JFrame {


/**

* Creates new form FormattingGUI

*/

public fileFormatting() {

initComponents();

}


/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents

private void initComponents() {


inputName = new javax.swing.JTextField();

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

outputName = new javax.swing.JTextField();

jButton1 = new javax.swing.JButton();

jLabel3 = new javax.swing.JLabel();

jLabel4 = new javax.swing.JLabel();

columnsField = new javax.swing.JTextField();

jLabel5 = new javax.swing.JLabel();

widthField = new javax.swing.JTextField();

precisionField = new javax.swing.JTextField();

jScrollPane2 = new javax.swing.JScrollPane();

jTextArea1 = new javax.swing.JTextArea();


setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);


jLabel1.setText("Input File:");


jLabel2.setText("Output File");


jButton1.setText("Do it");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});


jLabel3.setText("# of Columns");


jLabel4.setText("Width");


jLabel5.setText("Precision");


jTextArea1.setColumns(20);

jTextArea1.setFont(new java.awt.Font("Courier", 0, 12)); // NOI18N

jTextArea1.setRows(5);

jScrollPane2.setViewportView(jTextArea1);


javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(32, 32, 32)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel1)

.addComponent(inputName, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(62, 62, 62)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel2)

.addComponent(outputName, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

.addComponent(jButton1)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(columnsField)

.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel4)

.addComponent(widthField, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(precisionField)

.addComponent(jLabel5))

.addGap(21, 21, 21)))))

.addGroup(layout.createSequentialGroup()

.addGap(23, 23, 23)

.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addContainerGap(24, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(19, 19, 19)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

.addGroup(layout.createSequentialGroup()

.addComponent(jLabel2)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(outputName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(layout.createSequentialGroup()

.addComponent(jLabel1)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(inputName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel3)

.addComponent(jLabel4)

.addComponent(jLabel5))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(columnsField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(widthField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(precisionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jButton1)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(34, Short.MAX_VALUE))

);


pack();

}// </editor-fold>//GEN-END:initComponents


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

int columns, width, precision;


try {

columns = Integer.parseInt(columnsField.getText()); // gets string from columnsField, parses it to an integer and assigns it to columns variable

width = Integer.parseInt(widthField.getText());// gets string from widthField, parses it to an integer and assigns it to width variable

precision = Integer.parseInt(precisionField.getText()); // gets string from precisionField, parses it to an integer and assigns it to precision variable

String inputName = new File(this.inputName.getText()).getAbsolutePath();

File inFile = new File(inputName);

if (columns < 0 || columns > 5) {

throw new Exception("Column range must be 1-5");

}


if (!inFile.exists() || !inFile.canRead()) {

throw new IOException("Cannot read the input file specified");

}


String outputName = new File(this.outputName.getText()).getAbsolutePath();

File outFile = new File(outputName);

if (outFile.exists()) {

throw new IOException("File name specified already exists");

}


processFile(inFile, outFile, columns, width, precision);


} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(this, "Please correct the form information", "Bad Input", JOptionPane.WARNING_MESSAGE);

} catch (IOException ex) {

JOptionPane.showMessageDialog(this, ex.getMessage(), "Bad Files", JOptionPane.WARNING_MESSAGE);

} catch (Exception ex){

JOptionPane.showMessageDialog(this, ex.getMessage(), "Detected Error", JOptionPane.WARNING_MESSAGE);

}

}//GEN-LAST:event_jButton1ActionPerformed

private void processFile(File in, File out, int col, int w, int pre) throws Exception {


Scanner file = new Scanner(in);

PrintWriter writer = new PrintWriter(out);


double value;

String format = String.format("%%%d.%df", w, pre);

int count = 0;


while (file.hasNextDouble()) {

value = file.nextDouble();


String formattedNumber = String.format(format, value);

writer.print(formattedNumber);

jTextArea1.append(formattedNumber);

count ++;

if (count == col) {

jTextArea1.append("\n");

writer.print("\n");

count = 0;

}

}

writer.close();

file.close();

}


/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

}

}

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(fileFormatting.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(fileFormatting.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(fileFormatting.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(fileFormatting.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

}

//</editor-fold>

//</editor-fold>


/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new fileFormatting().setVisible(true);

}

});

}


// Variables declaration - do not modify//GEN-BEGIN:variables

private javax.swing.JTextField columnsField;

private javax.swing.JTextField inputName;

private javax.swing.JButton jButton1;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JScrollPane jScrollPane2;

private javax.swing.JTextArea jTextArea1;

private javax.swing.JTextField outputName;

private javax.swing.JTextField precisionField;

private javax.swing.JTextField widthField;

// End of variables declaration//GEN-END:variables

}


bottom of page