Converting tabs to spaces

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

Teacher wrote:
My standard answer: You decide how many spaces = 1 tab for conversion purposes. If you want to substitute 4 space characters for one '\t', make it so (and vice versa, as well).Maybe I'm over thinking it. I wrote my teacher and this is how he replied. If you take that exactly at face value, then just replacing x amount of spaces with a tab is trivial. However, I'd like to keep working on my interpretation of the question as I think preservation of the spacing of the original document is important. Here is what I've managed to put together so far and the issues I'm having. The biggest problem I'm having at this stage is that the first character AFTER the spaces is getting eaten by the sb.replace call. I can't figure out why this is happening. If I reduce count by one (which should move back the substring being replaced by one character) then it STILL gets eaten and now there is a space after the tab. I've spent too long looking at this and I'm sure it's something simple I'm missing. I'll cool my brain for awhile and come back.
P.S. Ignore the comments, they are diagnostic for me but I left them in in case anyone wanted to use them.
//sb is a stringbuffer holding the current line read in from the file
                                       //We have to ignore spaces at the beginning of the line because 0 -1 causes index out of bounds error
                         if(i%8 == 0 && !(i==0) && line.charAt(i-1) == ' ')
                              //System.out.println("Character at index " + (i-1) + " is a(n) |" + line.charAt(i-1) + "|");
                                               //Start the index at the space character
                              int index = i-1;
                              int count = 0;
                              //System.out.println("i="+i+"index="+index);
                                               //go backwards, counting spaces, until we find how many
                              while(line.charAt(index) == ' ')
                                   index--;
                                   count++;
                                   //System.out.println("Counting spaces! Index is now " + index + ", count is now " +count);
                                               //increase index by one (If we don't do this, the last character before all the spaces gets eaten
                              index++;
                              //System.out.println("Replacing substring: |" +line.substring(index, index + count)+ "|\nStarting index: "+index+"\nEnding index: "+(index + count));
                              sb.replace(index, index + count, "\t");
                         else
                         //If not a space, just copy it
                              sb.append(line.charAt(i));

Similar Messages

  • How to convert tabs between the words in a String to a single space in java

    I have a string with more number of tabs in between them, the thing I need to do is that I need to convert all those tabs into a single space.
    I used replaceAll(“/t”,” “); but the problem is that it was converting the tabs into spaces but if we have a 3 tabs in between 2 words then this 3 tabs are converting into 3 spaces but I need to have only one space.

    user548049,
    How is your question related to the topic of this forum: Oracle Database-embedded JVM?
    Anyway, you need to use the greedy qualifier: +, like so:
    replaceAll("\\t+"," ")Good Luck,
    Avi.

  • Bug with Show Whitespace and tab and space characters in SQL comments

    If Preferences > Code Editor > Display > Show Whitespace Characters is checked, and I type the following in SQL Worksheet:
    --A[tab]B[space]C
    It renders with two spaces between B and C. The first one is a blank space without the light dot character used to signify a space character, and the second space is filled with the dot character. The caret is then blinking before the C instead of after it:
    --A[tab]B[space][dot][|]C
    Further selection actions and editing in the region produce "corrupted" results. I've tried changing fonts, but there was no change to the behavior. Multiple tabs before the B produce multiple blank spaces immediately after it, and when placed at the end of the line the caret is then shown another space to the left of the C:
    --A[tab][tab]B[space][space][|][dot]C
    If I turn off Show Whitespace Characters the rendering immediately corrects, and caret placement, selection action, and editing behaviors all work as expected.
    This is observed on OS X with both the Mac OS X and Oracle/Fusion Blue look and feels.
    Ian
    About
    Oracle SQL Developer 3.0.04
    Version 3.0.04
    Build MAIN-04.34
    Copyright © 2005, 2011 Oracle. All Rights Reserved.
    IDE Version: 11.1.1.4.37.59.31
    Product ID: oracle.sqldeveloper
    Product Version: 11.1.2.04.34
    Version
    Component     Version
    =========     =======
    Java(TM) Platform     1.6.0_24
    Oracle IDE     3.0.04.34
    Versioning Support     3.0.04.34
    Properties
    Name     Value
    ====     =====
    apple.awt.graphics.UseOpenGL     false
    apple.awt.graphics.UseQuartz     false
    apple.laf.useScreenMenuBar     true
    awt.nativeDoubleBuffering     true
    awt.toolkit     apple.awt.CToolkit
    class.load.environment     oracle.ide.boot.IdeClassLoadEnvironment
    class.load.log.level     CONFIG
    class.transfer     delegate
    com.apple.macos.smallTabs     true
    com.apple.mrj.application.apple.menu.about.name     SQL_Developer
    com.apple.mrj.application.growbox.intrudes     false
    file.encoding     MacRoman
    file.encoding.pkg     sun.io
    file.separator     /
    ftp.nonProxyHosts     local|*.local|169.254/16|*.169.254/16
    gopherProxySet     false
    ice.browser.forcegc     false
    ice.pilots.html4.ignoreNonGenericFonts     true
    ice.pilots.html4.tileOptThreshold     0
    ide.AssertTracingDisabled     true
    ide.bootstrap.start     1309201485440911000
    ide.build     MAIN-04.34
    ide.conf     /Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper/bin/sqldeveloper.conf
    ide.config_pathname     /Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper/bin/sqldeveloper.conf
    ide.debugbuild     false
    ide.devbuild     false
    ide.extension.search.path     sqldeveloper/extensions:jdev/extensions:ide/extensions
    ide.firstrun     true
    ide.java.minversion     1.6.0_04
    ide.main.class     oracle.ide.boot.IdeLauncher
    ide.patches.dir     ide/lib/patches
    ide.pref.dir     /Users/ibrandt/.sqldeveloper
    ide.product     oracle.sqldeveloper
    ide.splash.screen     splash.gif
    ide.startingcwd     "/Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper/bin"
    ide.user.dir     /Users/ibrandt/.sqldeveloper
    ide.user.dir.var     IDE_USER_DIR
    ide.vcs.noapplications     true
    ide.work.dir     /Users/ibrandt/sqldeveloper
    ilog.propagatesPropertyEditors     false
    java.awt.graphicsenv     apple.awt.CGraphicsEnvironment
    java.awt.printerjob     apple.awt.CPrinterJob
    java.class.path     ../../ide/lib/ide-boot.jar
    java.class.version     50.0
    java.endorsed.dirs     /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/endorsed
    java.ext.dirs     /Library/Java/Extensions:/System/Library/Java/Extensions:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/ext
    java.home     /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
    java.io.tmpdir     /var/folders/rq/rqQtue9lEpGAwCKh2hL8MU+++TM/-Tmp-/
    java.library.path     .:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java
    java.naming.factory.initial     oracle.javatools.jndi.LocalInitialContextFactory
    java.protocol.handler.pkgs     oracle.jdevimpl.handler
    java.runtime.name     Java(TM) SE Runtime Environment
    java.runtime.version     1.6.0_24-b07-334-10M3326
    java.specification.name     Java Platform API Specification
    java.specification.vendor     Sun Microsystems Inc.
    java.specification.version     1.6
    java.util.logging.config.file     logging.conf
    java.vendor     Apple Inc.
    java.vendor.url     http://www.apple.com/
    java.vendor.url.bug     http://bugreport.apple.com/
    java.version     1.6.0_24
    java.vm.info     mixed mode
    java.vm.name     Java HotSpot(TM) 64-Bit Server VM
    java.vm.specification.name     Java Virtual Machine Specification
    java.vm.specification.vendor     Sun Microsystems Inc.
    java.vm.specification.version     1.0
    java.vm.vendor     Apple Inc.
    java.vm.version     19.1-b02-334
    jdbc.library     /Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper/jdbc/lib/ojdbc6.jar
    line.separator     \n
    log.file.name     /Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper/extensions/oracle.datamodeler/log/datamodeler.log
    mrj.build     10M3326
    mrj.version     1060.1.6.0_24-334
    oracle.home     /Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper
    oracle.ide.util.AddinPolicyUtils.OVERRIDE_FLAG     true
    oracle.jdbc.mapDateToTimestamp     false
    oracle.translated.locales     de,es,fr,it,ja,ko,pt_BR,zh_CN,zh_TW
    oracle.xdkjava.compatibility.version     9.0.4
    orai18n.library     /Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper/jlib/orai18n.jar
    os.arch     x86_64
    os.name     Mac OS X
    os.version     10.6.8
    path.separator     :
    reserved_filenames     con,aux,prn,lpt1,lpt2,lpt3,lpt4,lpt5,lpt6,lpt7,lpt8,lpt9,com1,com2,com3,com4,com5,com6,com7,com8,com9,conin$,conout,conout$
    socksNonProxyHosts     local|*.local|169.254/16|*.169.254/16
    sqldev.debug     false
    sun.arch.data.model     64
    sun.awt.exception.handler     apple.awt.CToolkit$EventQueueExceptionHandler
    sun.boot.class.path     ../../rdbms/jlib/ojdi.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar:
    /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Resources/Java/JavaRuntimeSupport.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/ui.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/sunrsasign.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsse.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jce.jar:
    /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/charsets.jar
    sun.boot.library.path     /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Libraries
    sun.cpu.endian     little
    sun.cpu.isalist     
    sun.io.unicode.encoding     UnicodeLittle
    sun.java.launcher     SUN_STANDARD
    sun.java2d.ddoffscreen     false
    sun.jnu.encoding     MacRoman
    sun.management.compiler     HotSpot 64-Bit Server Compiler
    sun.os.patch.level     unknown
    svnkit.sax.useDefault     true
    user.country     US
    user.dir     /Applications/Development/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper/bin
    user.home     /Users/ibrandt
    user.language     en
    user.name     ibrandt
    user.timezone     America/Los_Angeles
    windows.shell.font.languages     
    Extensions
    Name     Identifier     Version     Status
    ====     ==========     =======     ======
    Check For Updates     oracle.ide.webupdate     11.1.1.4.37.59.31     Loaded
    Code Editor     oracle.ide.ceditor     11.1.1.4.37.59.31     Loaded
    Component Palette     oracle.ide.palette1     11.1.1.4.37.59.31     Loaded
    Data Miner     oracle.dmt.dataminer     11.2.0.1.10.109     Loaded
    Database Connection Support     oracle.jdeveloper.db.connection     11.1.1.4.37.59.31     Loaded
    Database Object Explorers     oracle.ide.db.explorer     11.1.1.4.37.59.31     Loaded
    Database UI     oracle.ide.db     11.1.1.4.37.59.31     Loaded
    Diagram Framework     oracle.diagram     11.1.1.4.37.59.31     Loaded
    Diagram Javadoc Extension     oracle.diagram.javadoc     11.1.1.4.37.59.31     Loaded
    Diagram Thumbnail     oracle.diagram.thumbnail     11.1.1.4.37.59.31     Loaded
    Diff/Merge     oracle.ide.diffmerge     11.1.1.4.37.59.31     Loaded
    Extended IDE Platform     oracle.javacore     11.1.1.4.37.59.31     Loaded
    External Tools     oracle.ide.externaltools     11.1.1.4.37.59.31     Loaded
    File Support     oracle.ide.files     11.1.1.4.37.59.31     Loaded
    Help System     oracle.ide.help     11.1.1.4.37.59.31     Loaded
    History Support     oracle.jdeveloper.history     11.1.1.4.37.59.31     Loaded
    Import/Export Support     oracle.ide.importexport     11.1.1.4.37.59.31     Loaded
    Index Migrator support     oracle.ideimpl.indexing-migrator     11.1.1.4.37.59.31     Loaded
    JDeveloper Runner     oracle.jdeveloper.runner     11.1.1.4.37.59.31     Loaded
    JViews Registration Addin     oracle.diagram.registration     11.1.1.4.37.59.31     Loaded
    Log Window     oracle.ide.log     11.1.1.4.37.59.31     Loaded
    Mac OS X Adapter     oracle.ideimpl.apple     11.1.1.4.37.59.31     Loaded
    Navigator     oracle.ide.navigator     11.1.1.4.37.59.31     Loaded
    Object Gallery     oracle.ide.gallery     11.1.1.4.37.59.31     Loaded
    Oracle IDE     oracle.ide     11.1.1.4.37.59.31     Loaded
    Oracle SQL Developer     oracle.sqldeveloper     11.1.2.04.34     Loaded
    Oracle SQL Developer - 3rd Party Database Browsers     oracle.sqldeveloper.thirdparty.browsers     11.1.1.04.34     Loaded
    Oracle SQL Developer - DBA Navigator     oracle.sqldeveloper.dbanavigator     11.1.1.04.34     Loaded
    Oracle SQL Developer - Extras     oracle.sqldeveloper.extras     1.1.1.04.34     Loaded
    Oracle SQL Developer - File Navigator     oracle.sqldeveloper.filenavigator     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Antlr3 Translator     oracle.sqldeveloper.migration.translation.core_antlr3     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Application Migration     oracle.sqldeveloper.migration.application     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Core     oracle.sqldeveloper.migration     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations DB2     oracle.sqldeveloper.migration.db2     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations DB2 Translator     oracle.sqldeveloper.migration.translation.db2     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Microsoft Access     oracle.sqldeveloper.migration.msaccess     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Microsoft SQL Server     oracle.sqldeveloper.migration.sqlserver     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations MySQL     oracle.sqldeveloper.migration.mysql     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Sybase Adaptive Server     oracle.sqldeveloper.migration.sybase     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations T-SQL Translator     oracle.sqldeveloper.migration.translation.core     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Teradata     oracle.sqldeveloper.migration.teradata     11.1.1.04.34     Loaded
    Oracle SQL Developer - Migrations Translation UI     oracle.sqldeveloper.migration.translation.gui     11.1.1.04.34     Loaded
    Oracle SQL Developer - Object Viewer     oracle.sqldeveloper.oviewer     11.1.1.04.34     Loaded
    Oracle SQL Developer - Real Time SQL Monitoring     oracle.sqldeveloper.sqlmonitor     11.1.1.04.34     Loaded
    Oracle SQL Developer - Reports     oracle.sqldeveloper.report     11.1.1.04.34     Loaded
    Oracle SQL Developer - Scheduler     oracle.sqldeveloper.scheduler     11.1.1.04.34     Loaded
    Oracle SQL Developer - Schema Browser     oracle.sqldeveloper.schemabrowser     11.1.1.04.34     Loaded
    Oracle SQL Developer - SearchBar     oracle.sqldeveloper.searchbar     11.1.1.04.34     Loaded
    Oracle SQL Developer - Snippet     oracle.sqldeveloper.snippet     11.1.1.04.34     Loaded
    Oracle SQL Developer - Spatial     oracle.sqldeveloper.spatial     11.1.1.04.34     Loaded
    Oracle SQL Developer - TimesTen     oracle.sqldeveloper.timesten     2.0.0.04.34     Loaded
    Oracle SQL Developer - Tuning     oracle.sqldeveloper.tuning     11.1.1.04.34     Loaded
    Oracle SQL Developer - Unit Test     oracle.sqldeveloper.unit_test     11.1.1.04.34     Loaded
    Oracle SQL Developer - User Extensions Support     oracle.sqldeveloper.userextensions     11.1.1.04.34     Loaded
    Oracle SQL Developer - Worksheet v2     oracle.sqldeveloper.worksheet     11.1.1.04.34     Loaded
    Oracle SQL Developer - XML Schema     oracle.sqldeveloper.xmlschema     11.1.1.04.34     Loaded
    Oracle SQL Developer Data Modeler     oracle.datamodeler     3.0.0.665.2     Loaded
    Oracle SQL Developer Data Modeler - Reports     oracle.sqldeveloper.datamodeler_reports     11.1.1.04.34     Loaded
    PROBE Debugger     oracle.jdeveloper.db.debug.probe     11.1.1.4.37.59.31     Loaded
    Peek     oracle.ide.peek     11.1.1.4.37.59.31     Loaded
    Persistent Storage     oracle.ide.persistence     11.1.1.4.37.59.31     Loaded
    Property Inspector     oracle.ide.inspector     11.1.1.4.37.59.31     Loaded
    QuickDiff     oracle.ide.quickdiff     11.1.1.4.37.59.31     Loaded
    Replace With     oracle.ide.replace     11.1.1.4.37.59.31     Loaded
    Runner     oracle.ide.runner     11.1.1.4.37.59.31     Loaded
    VHV     oracle.ide.vhv     11.1.1.4.37.59.31     Loaded
    Versioning Support     oracle.jdeveloper.vcs     11.1.1.4.37.59.31     Loaded
    Versioning Support for Subversion     oracle.jdeveloper.subversion     11.1.1.4.37.59.31     Loaded
    Virtual File System     oracle.ide.vfs     11.1.1.4.37.59.31     Loaded
    Web Browser and Proxy     oracle.ide.webbrowser     11.1.1.4.37.59.31     Loaded
    XML Editing Framework IDE Extension     oracle.ide.xmlef     11.1.1.4.37.59.31     Loaded
    audit     oracle.ide.audit     11.1.1.4.37.59.31     Loaded
    classpath: protocol handler extension     oracle.jdeveloper.classpath     11.1.1.0.0     Loaded
    jdukshare     oracle.bm.jdukshare     11.1.1.4.37.59.31     Loaded
    mof-xmi     oracle.mof.xmi     11.1.1.4.37.59.31     Loaded
    oracle.ide.dependency     oracle.ide.dependency     11.1.1.4.37.59.31     Loaded
    oracle.ide.indexing     oracle.ide.indexing     11.1.1.4.37.59.31     Loaded
    palette2     oracle.ide.palette2     11.1.1.4.37.59.31     Loaded
    status     oracle.ide.status     11.1.1.4.37.59.31     Loaded

    are you using an "Expert Mode" query or not?
    With normal mode, the query is stored in an XML attribute.
    With expert mode, it's stored in a CDATA Section, which allows it to respect all user-spacing and newlines.
    XML attribute values are forced by the XML 1.0 spec to be normalized, and this is done by the parser when they are read in. That might account for your different in space treatment.

  • How do I save/export as a TAB or SPACE delimited text file?

    Just upgraded from Apple Works to iWorks. The only text exporting option I see is .csv. Comma separation really screws up my needs. Is there a way to export as plain text? TAB or SPACE delimited?

    Why not using the good old
    --[SCRIPT clipboard2textFile]
    on run
    set tsv to the clipboard as text
    set nomDuFichier to (do shell script "date " & quote & "+P%Y%m%d-%H%M%S" & quote) & ".txt"
    set p2d to path to documents folder as text
    tell application "System Events"
    make new file at end of folder p2d with properties {name:nomDuFichier, file type:"TEXT"}
    end tell -- System Events
    set leDoc to p2d & nomDuFichier
    write tsv to file leDoc
    end run
    --[/SCRIPT]
    I have it installed as:
    <startupVolume>:Users:<my account>:Library:Scripts:clipboard2textFile.scpt
    No need for an extra application.
    Copy to clipboard,
    trigger the script from the menu,
    the text file is available on the desktop.
    Yvan KOENIG (VALLAURIS, France.) lundi 24 août 2009 16:25:13

  • [svn:fx-trunk] 11450: Cleaning up the whitespace in these 3 files ( tabs to spaces).

    Revision: 11450
    Author:   [email protected]
    Date:     2009-11-04 17:10:56 -0800 (Wed, 04 Nov 2009)
    Log Message:
    Cleaning up the whitespace in these 3 files (tabs to spaces).
    QE notes: No
    Doc notes: No
    Bugs: No
    Reviewer: Me
    Tests run: Checkintests
    Is noteworthy for integration: No
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/Group.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/supportClasses/GroupBase.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/GraphicEleme nt.as

    Thats good news.

  • Remap tab to space

    I'm simply trying to remap the tab key to input spaces, but aren't having much luck- any pointers would be appreciated:
    public class MyTextPane
        extends JTextPane{
        public MyTextPane() {
          super();
          InputMap im = this.getInputMap();
          ActionMap am = this.getActionMap();
          //  Have the tab key work the same as the space key
          KeyStroke tab = KeyStroke.getKeyStroke("TAB");
          KeyStroke space = KeyStroke.getKeyStroke("SPACE");
          im.put(tab, im.get(space));
          am.put(im.get(space), am.get(space));
    }I've also tried overriding the processKeyBinding method, but I get two spaces for every one I want:
    public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
        if (ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) {// TAB
          ks = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,  0);
          MyStyledDoc doc = (MyStyledDoc) this.getDocument();
         int pos = this.getCaretPosition();
          try{
             doc.insertString(pos, " ", null);
          }catch(BadLocationException ble){}
        return super.processKeyBinding(ks,e,condition,pressed);
      }

    I'm simply trying to remap the tab key to input
    spaces, but aren't having much luck- any pointers
    would be appreciated:There is no entry in the ActionMap associated with the SPACE key, so your code does nothing but remove the action associated with TAB.
    Here's some code that inserts a single SPACE when TAB is pressed:
    KeyStroke tabStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0);
            Action spaceAction = new AbstractAction() {
                public void actionPerformed(ActionEvent ae) {
                    try {
                        textPane.getDocument().insertString(textPane.getCaretPosition(), " ", null);
                    } catch (BadLocationException ble) {
                        System.out.println("This error shoul be impossible");
                        ble.printStackTrace();
            textPane.getInputMap().put(tabStroke, spaceAction);

  • JDOM attribute converts tab characters to a space separator

    I am using a well-formed xml file to parse delimited data. I am passing a tab character as an attribute to an element called delimiter. When the text values from my elements are read in, the tab character is properly read. The tab character that is stored in the delimiter attribute is read in as a space separator rather than a tab. Is this a bug or should I be parsing the attribute differntly? Below is my sample code and xml stream:
    public static void main(String args[]) {
    try{
    File file = new File("c:\\output.xml");
    Element rootElement = getRootElement(new FileReader(file));
    System.out.println("Element text is tab: " + rootElement.getText().equals("\t"));
    System.out.println("Attribute text is tab: " + rootElement.getAttributeValue("delimiter").equals("\t"));
    System.out.println("Attribute type: " + Character.getType(rootElement.getAttributeValue("delimiter").charAt(0)));
    //returns type 12 (space separator)
    }catch (Exception e) {}
    public static Element getRootElement(Reader reader) throws JDOMException, FileNotFoundException{
    Element rootElement = null;
    SAXBuilder builder = new SAXBuilder();
    try {
    // Generate JDom Document
    org.jdom.Document jdomDoc = builder.build(reader);
    rootElement = jdomDoc.getRootElement();
    }catch (JDOMException e) { throw new JDOMException(e.getMessage()); } // indicates a well-formedness or validity error
    return rootElement;
    Below is the xml data that I used to emulate this test:
    <DELIM_TEST delimiter="     ">     </DELIM_TEST>
    NOTE: replace the delimiter and text values with a tab character if the html post converts them to a space.

    I don't think it's a bug, I think it's a feature. Have a look at the XML specs, which are here:
    http://www.w3.org/TR/REC-xml#sec-white-space
    and see if section 2.10, White Space Handling, describes what you are describing. I found it rather obscure. Also, Michael Kay's book on XSLT has about six pages devoted to white space handling, and at one point it says
    "The XML parser will normalize attribute values. A tab or newline will always be replaced by a single space, unless it is written as a character reference..."

  • Convert tab delimited  file content into an xml

    Hi,
    I am completely new to java and i am trying to create a tree of an
    output i have. generally the output is tab delimited and i have a
    sample output in the following link
    http://jena.sourceforge.net/ontology/examples/class-hierarchy/output.txt
    I want to create an xml out of it in the tree format as below
    <Class :Thing>
    (/t) <Class :KoalaWithPhD>
    (/t) <Class :MaleStudentWith3Daughters>
    (/t) <Class :Habitat>
    </Class :Thing>
    note i have added (/t ) just to explain u that kolawithphd is child node of thing ...and so on.
    Can someone throw in a simple code snipet that can help me do this.
    Really appreciate your help
    Thanks
    aks

    You need to detect the amount of indent, and whether the current line is more or less indented. You also need a stack to hold the indents of the previous lines, so the converter knows which one it's matching.
    Assuming the output is like the jena example - spaces only as indent and no non-xml-attribute-value characters in the class names, one possible converter would look like:import java.io.*;
    import java.util.*;
    public class ClassesToXml {
      public static void main (String[] args) {
        try {
          BufferedReader in = null;
          try {
            in = new BufferedReader(new FileReader(args[0]));
            String line;
            int previousIndent = -1;
            LinkedList stack = new LinkedList();
            System.out.print("<classes");
            while ((line = in.readLine()) != null) {
              final int indent = indent(line);
              if (indent <= previousIndent) {
                System.out.println("/>");
                while (indent < previousIndent) {
                  System.out.println("</class>");
                  previousIndent = ((Integer)stack.getFirst()).intValue();
                  stack.removeFirst();
              } else {
                System.out.println(">");
                stack.addFirst(new Integer(previousIndent));
                previousIndent = indent;
              System.out.print("<class name='" +
                               line.substring(line.indexOf("Class ") + 6).trim() +
            System.out.println("/>");
            while (stack.size() > 1) {
              System.out.println("</class>");
              stack.removeFirst();
            System.out.println("</classes>");
          } finally {
            if (in != null) {
              in.close();
        } catch (IOException ioe) {
          ioe.printStackTrace(System.out);
      static int indent (String line) {
        final int length = line.length();
        for (int indent = 0; indent < length; indent++) {
          if (line.charAt(indent) != ' ') {
            return indent;
        return length;
    }Pete

  • Convert tab separated text to non-trivial xml. (pwsafe -- KeePassx)

    I'd like to take the output of `pwsafe --exportdb > database.txt` and convert it to a KeePassX XML friendly format (feature request in pwsafe).
    I found flat file converter but the syntax is beyond me with this example.  Solutions are welcomed.
    More details
    Here is the pwsafe --> KeePassX XML translations.  The pwsafe export is simply a txt file with 6 fields (the first field can be ignored):
    uuid= doesn't translate
    group= group>title
    name= entry>title
    login= entry>username
    passwd= entry>password
    notes= entry>comment
    Example txt file for conversion (exported from pwsafe):
    # passwordsafe version 2.0 database"
    uuid group name login passwd notes
    "123d9-daf-df-3423423" "retail" "amazon" "myamazonuser" "sjfJ849" "superfluous comment"
    "4599d934-dsfs-324" "retail" "netflix" "netflixuser" "dj3W$#" ""
    "4kdfkd-434-jj" "email" "gmail" "mygmail" "dfkpass" ""
    Example xml in keepassx xml:
    <!DOCTYPE KEEPASSX_DATABASE>
    <database>
    <group>
    <title>Internet</title>
    <entry>
    <title>github</title>
    <username>githubusername</username>
    <password>githubpassword</password>
    <comment>optional comment</comment>
    </entry>
    </group>
    <group>
    <title>retail</title>
    <entry>
    <title>amazon</title>
    <username>username</username>
    <password>myamazonpw</password>
    </entry>
    </group>
    <group>
    <title>retail</title>
    <entry>
    <title>netflix</title>
    <username>username</username>
    <password>mynfxpw</password>
    </entry>
    </group>
    </database>
    Last edited by graysky (2015-06-14 18:27:17)

    It seems that ffe does not work quite well with tab/space separated list (at least I was not able to get it working). However you can use sed to replace tabs with commas:
    sed -e "s/\t/,/g" input.txt | ffe -c pwsafe.rc -s example.txt -l 2>/dev/null
    and this is pwsafe.rc
    structure pwsafe {
    type separated , *
    output group
    quoted
    header first
    record line {
    field uuid * * noprint
    field title
    field title * * entry
    field username * * entry
    field passwordd * * entry
    field comment * * entry
    output noprint {
    data ""
    no-data-print no
    output entry {
    data " <%n>%t</%n>\n"
    no-data-print no
    output group {
    file_header "<!DOCTYPE KEEPASSX_DATABASE>\n <database>\n"
    record_header " <group>\n"
    data " <%n>%t</%n>\n <entry>\n"
    record_trailer " <entry>\n </group>\n"
    file_trailer "</database>\n"
    no-data-print no
    If you are not bound to ffe, maybe it is easier to use a python script which is simpler to modify and it is more flexible. Something like the following should work:
    #!/usr/bin/python
    import sys
    from xml.dom import minidom
    class Converter(object):
    def __init__(self, filename):
    self.url = filename
    def convert(self):
    inp_f = open(self.url, 'r')
    data = inp_f.readlines()
    inp_f.close()
    # xml document model
    doc = minidom.Document()
    root = doc.createElement('database')
    doc.appendChild(root)
    for line in data:
    if '"' not in line:
    continue
    fields = line.split('\t')
    if len(fields) < 6:
    continue
    # uuid = fields[0].strip('"') # unused
    group = fields[1].strip('" ')
    name = fields[2].strip('" ')
    login = fields[3].strip('" ')
    passwd = fields[4].strip('" ')
    notes = fields[5].strip('" \n')
    group_node = doc.createElement('group')
    root.appendChild(group_node)
    # <group>
    group_title_node = doc.createElement('title')
    group_node.appendChild(group_title_node)
    group_title_node.appendChild(doc.createTextNode(group))
    # one <entry> per <group>
    entry_node = doc.createElement('entry')
    group_node.appendChild(entry_node)
    # <entry> -> <title>
    entry_title_node = doc.createElement('title')
    entry_title_node.appendChild(doc.createTextNode(name))
    entry_node.appendChild(entry_title_node)
    # <entry> -> <username>
    entry_uname_node = doc.createElement('username')
    entry_uname_node.appendChild(doc.createTextNode(login))
    entry_node.appendChild(entry_uname_node)
    # <entry> -> <password>
    entry_passwd_node = doc.createElement('password')
    entry_passwd_node.appendChild(doc.createTextNode(passwd))
    entry_node.appendChild(entry_passwd_node)
    # <entry> -> <comments>
    entry_comment_node = doc.createElement('comment')
    entry_comment_node.appendChild(doc.createTextNode(notes))
    entry_node.appendChild(entry_comment_node)
    print('<!DOCTYPE KEEPASSX_DATABASE>')
    print(root.toprettyxml(' ', '\n'))
    if __name__ == "__main__":
    try:
    ifname = sys.argv[1]
    except IndexError:
    print("Input file name required")
    sys.exit(1)
    cc = Converter(ifname)
    cc.convert()
    NOTE: I'm assuming from the example you posted that every <group> node contains only one <entry> child node.
    --edit[0]: corrected a typo in the python code (just realized that it is <comment> instead of <comments ) and made the parsing function more reliable
    Last edited by mauritiusdadd (2015-06-15 09:29:01)

  • Converting a single space between sentences with two spaces.

    Hi,
    I'd like to convert all single whitespaces after a sentence to two whitespaces, e.g. This is a sentence! The next sentence is separated by two spaces. This would result in the conventional style of two spaces between sentences, unlike html style. I want to find either a .,?, or ! followed by one whitespace, followed by a capital letter, so: "[.|?|!] [A-Z]". Then I want to just replace this with the same thing except two spaces. If I do this:
                        textString = textString.replaceAll(". [A-Z]", ". [A-Z]");
    it finds these matches, but it literally prints out these:
    How about DeLillo[.|?|!] [A-Z] still haven't read him[.|?|!] [A-Z]r Saul Bellow[.|?|!] [A-Z] told you I like Herzog a lot...maybe
    thanks for your help!
    -Won

    You don't want to add a space if there is already a second space. The following will turn any number of spaces after the sentence into two spaces. Note if the whitespaces include a \n\n (paragraph mark) it will turn everything into one long paragraph.
    replaceAll("([\\.\\?!])\\s+", "$1  ");

  • Double click in the empty tab bar space to open a new tab.

    I upgraded to Firefox 7 today, and now if I try to click in the empty space on the tab bar to the right of the current tabs I no longer get a new tab.
    Is there a way to re-enable this feature?

    Sorry but this is annoying! I have been using Firefox for a long time and all of a sudden an update (7.0) stops the doubleclick in the tabs bar.
    I have Firefox both at the office and at home. Strangely, at home I´ve got this problem but at the office I haven´t. I´ve got XP at the office and Vista at home.
    And please don´t tell me to get used to the plus button or the mouse middle button.

  • Command-tab Finder + Spaces nuttiness

    Hi Folks. New to Mac OS X Leopard (10.5.2) on a Macbook pro, coming from Windows XP. The command-tab switch feature on my Mac sometimes does something strange when Spaces is combined with multiple Finder windows, and I'd love to know how to make it work in a more intuitive manner.
    Please tell me if you've experienced this: Sometimes when I switch back and forth from an application (e.g., Firefox) to the Finder with command-tab, the Finder window switched to is different each time - it seems to cycle through each window in each space. The only work-around is to use command-` .
    Unfortunately, while writing detailed steps to recreate this, it went away. Drat!
    Anyone seen this? Thanks in advance!
    matt

    Hi Folks. New to Mac OS X Leopard (10.5.2) on a Macbook pro, coming from Windows XP. The command-tab switch feature on my Mac sometimes does something strange when Spaces is combined with multiple Finder windows, and I'd love to know how to make it work in a more intuitive manner.
    Please tell me if you've experienced this: Sometimes when I switch back and forth from an application (e.g., Firefox) to the Finder with command-tab, the Finder window switched to is different each time - it seems to cycle through each window in each space. The only work-around is to use command-` .
    Unfortunately, while writing detailed steps to recreate this, it went away. Drat!
    Anyone seen this? Thanks in advance!
    matt

  • Convert to 128kbps space calculated incorrectly

    I've recently re-copied all my CDs up to 320K VBR and have selected the 128kbps option in iTunes 10.1
    When I last synch'd my iPhone it told me I would have about 8GB left and at the end of the sync it confirmed I had 8GB free space.
    I reset the iPhone and checked again...this time it says 2.5 GB free and if I UNCHECK the option to convert high bitrates to 128K, the free space goes UP to 8.1GB again.
    I left the 128k option ticked (2.5GB remaining) and hit sync again...the space increased to 8.1 GB until the sync copied a single song over then i decreased to 2.5GB free again.
    Next sync says 8.1GB free.
    iPhone is running 4.2.1
    Anybody know what's going on?

    Well that bites doesn't it?
    I've done a little bit of reading and I now have a theory as to why this is. iTunes does this for mobile phones too, and I think it's because mobile phones and the Shuffle cannot play all formats (the Shuffle cannot play Apple Lossless files) so iTunes includes this option for them. It seems a bit of an oversight not to have it for other iPods too.

  • Expose, Cmd Tab, Screenshot, Spaces all breaking

    Not sure what causes this, I thought it was sleeping but apparently not.
    All Expose, Cmd Tab, Screenshot and Spaces will all be fine but they theyll stop working and I also cannot reboot or log out, the Mac just wont.
    I have to go Terminal -> "sudo reboot" to force a restart.

    Couple of possibilities. The first thing I'd try is clearing your launchServices caches.
    Launch Terminal and copy & paste this at the command line to rebuild LaunchServices:
    Code:
    <pre class="alt2" style="margin:0px; padding:3px; border:1px inset; width:640px; height:34px; overflow:auto">/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchSe rvices.framework/Versions/A/Support/lsregister -kill -r -domain local -domain system -domain user</pre>
    Then press return. Wait until terminal returns to the command line. Quit Terminal. After that, log out and back in or restart. Let us know
    -mj

  • Global site edit -- change tabs to spaces in DW

    Is there a way in DW to do a site-wide change that replaces
    all the tabs in the code with spaces? I know you can do it page by
    page, but I was hoping for a faster way.
    Thanks!

    Tabs in the code? You mean in Code view?
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "isleta13" <[email protected]> wrote in
    message
    news:ehq595$c1e$[email protected]..
    > Is there a way in DW to do a site-wide change that
    replaces all the tabs
    > in the code with spaces? I know you can do it page by
    page, but I was
    > hoping for a faster way.
    >
    > Thanks!

Maybe you are looking for