Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Converting tabs to spaces

707697Apr 19 2009 — edited Apr 21 2009
Just so you all know, this is an assignment for school that I'm having trouble with.

One of the parts of this assignment is to convert spaces to tabs in a text file. However, we have to maintain the original spacing (otherwise it would be simple). I'm honestly baffled as to how this can be accomplished. I hope I'm along the right lines in trying to use StringBuilder but I can't quite get the spacing to come out right. So my question is, how do I replace the spaces with tabs, but maintain the spacing of the original file.

Here is my SSCCE
import java.util.Scanner;
import java.io.*;

public class SpacesToTabs
{
	public static void main(String[] args)
	{
		String line, fileName = null;
		StringBuilder sb = null;
		Scanner stdIn = new Scanner(System.in), in = null;
		BufferedWriter out = null;

		System.out.print("Enter filename[test.txt]: ");
		fileName = stdIn.nextLine();

		try
		{
			//In and Out objects
			in = new Scanner(new BufferedReader(new FileReader(fileName)));
			out = new BufferedWriter(new FileWriter(fileName.substring(0, fileName.indexOf('.')) + "_new" + fileName.substring(fileName.indexOf('.'), fileName.length())));
			while(in.hasNext())
			{
				//Read a line
				line = in.nextLine();
				//Make a new StringBuilder
				sb = new StringBuilder(line.length());
				//Loop through that line
				for(int i =0; i<line.length(); i++)
				{
					//If it's a space, replace it with a tab
					//this is where I'm confused as to how I can maintain the spacing
					if(line.charAt(i) == ' ')
					{
						sb.insert(i, '\t');
					}
					else
					//If not a space, just copy it
						sb.append(line.charAt(i));
				}
				//Write to the buffer
				out.write(sb.toString());
				out.newLine();
			}
		}
		catch(FileNotFoundException e)
		{
			System.err.println(e.getMessage());
		}
		catch(IOException e)
		{
			System.err.println(e.getMessage());
		}
		finally
		{
			try
			{
				//flush and close all streams
				out.flush();
				in.close();
				out.close();
			}
			catch(IOException e)
			{
				System.err.println(e.getMessage());
			}
		}
	}
}
And here is a test file (test.txt)
blah blah blah line 1   tab
blah blah blah line 2   tab
blah blah blah line 3   tab
blah blah blah line 4   tab
t       tab     tab     tab
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 19 2009
Added on Apr 19 2009
19 comments
935 views