0

am I still very new to java, only had one semester of it. I have my first internship and it isn't a programming internship, just a general IT internship Since it was only my first semester. My boss does not know Java, nor does anyone in the building. He knew I had some basic programming experience and told me to take a stab at the problem he is having. He has a report that is saved and the very last line, the very last character of the report is a character turn symbol, and we need remove that because it is giving us problems on the website. I am not sure if I am even on the right track, at this point I am just doing trial and error. Please help :D

 public class RemoveChar {

    public static void main(String[] args) throws FileNotFoundException {

    // Variables and stuff
    Scanner keyScan = new Scanner(System.in);
    JFrame frameOne = new JFrame ("File Name");
    Scanner fileScan = new Scanner(System.in);
    String fileName;

    // Ask user for file name
    System.out.print("What is the file full file name? ");
    fileName = fileScan.nextLine();

    // Add .txt if the user forgets to put it in the prompt
    if (!fileName.contains(".txt"))
        fileName += ".txt";

    //Test to see if file exists
    File myFile = new File(fileName);
    if(!myFile.exists()){
        System.out.println(fileName + " does not exist. ");
        System.exit(0);
    }

    fWriter = new FileWriter("config/lastWindow.txt", true);
    /*while(fileName.hasNext()){

    }
    File 
    BufferedReader inputFile = new BufferedReader(new FileReader("C:\\" +        fileScan));
    //Scanner reader = new Scanner (inputFile);
    */



  }

}
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
Joe Valenti
  • 11
  • 1
  • 5

3 Answers3

3

How big are the files? If they are not that large, you can read the entire file into a string and then chop off the last character:

//Set delimiter to end-of-string anchor \Z so that you can read the
//file in with just one call to next()
//from: http://stackoverflow.com/a/3403112/263004

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
String withoutLastCharacter = content.substring(0, content.length - 1);

Then you just need to write withoutLastCharacter out to the file.

Otherwise you need to read in the original file line by line and write it out to a temporary file, and then copy that file over the original one. However, if you are on the last line, you will chop off the last character. Here's some code that should give you an idea of the basic logic:

while(scanner.hasNextLine()) {
    String line = scanner.nextLine();

    //If this is the last line chop off the last character.
    if(!scanner.hasNextLine()) {
        line = line.substring(0, line.length - 1);
    }

    //Write line out to temporary file
    ...
}

You also mentioned that it doesn't have to be Java. If you're on Linux or Mac, you can just do this with sed:

sed -i '$s/.$//' <filename>

This will delete the last character of the last line of the file.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
1

Does this have to be a java problem? For something like this where it is basic file/string manipulation I prefer to use something like Perl. The below perl script will delete the last byte (or char in this case) from a file

    my $fsize = -s $filename;  
    # print $size."\n";
    open($FILE, "+<", $filename) or die $!; 
    seek $FILE, $size-2, SEEK_SET; 
    print $FILE ";";

    close $FILE;
Brian H
  • 1,033
  • 2
  • 9
  • 28
  • No, it doesn't have to be Java, just thought I would try it because I am trying to not slack and learn it the best I can. But if all else fails I will go ahead and try this thanks for the tip! – Joe Valenti Jun 10 '15 at 18:07
  • I love Perl, but I think it's overkill here. You can just use `sed` like so: `sed -i '$s/.$//' ` :) – Vivin Paliath Jun 10 '15 at 18:14
  • I believe Java is overkill here compared to Perl, but I believe you are right that Perl is overkill to sed – Brian H Jun 10 '15 at 18:15
  • @JoeValenti this may sound counterintuitive, but I firmly believe that you should **not** code a solution if there's a solution out there you can use as such (sed, perl or with code you can reuse from somewhere else - Commons IO is a good example for many Java file operations). In my book correct reuse is a much more important skill than lines/hour written. – fvu Jun 10 '15 at 18:16
  • @BrianMikeyHalbert Completely agree. For things like this I usually turn to perl (as you did) or use sed/tr – Vivin Paliath Jun 10 '15 at 18:21
  • 1
    @fvu I agree in general, but if OP is trying to learn programming (in Java), then I think it is alright since it will be a good learning-experience. But yes, in general there is no reason to reinvent. – Vivin Paliath Jun 10 '15 at 18:22
  • I just figured out that it is not nec. to ask the user for data anymore, the report is always the same file name and is just over written. I tried out this, when I open the file in Java, it doesn't actually recognize the turn symbol it shows up as a box with a question mark in it(the size of a normal char). Could this cause a problem String contentCred = new Scanner(new File("fp_dlr_credit")).useDelimiter("\\Z").next(); String withoutLastCharacter2 = contentCred.substring(0, contentCred.length()-1); – Joe Valenti Jun 10 '15 at 18:29
0
 static class CopyFileContent {

    public static void main(String[] args) {

        String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
        File myDir = new File(root + "/MyFolder");//create folder in internal storage
        myDir.mkdirs();// make directory
        File destFile = new File(myDir, FILENAME11);//making a new file in the folder
    /* Source file, from which content will be copied */
        File sourceFile1 = new File(myDir, FILENAME12);
        File sourceFile2 = new File(myDir, FILENAME13);
        File sourceFile3 = new File(myDir, FILENAME14);

    /* destination file, where the content to be pasted */
        // File destFile = new File(FILENAME);

    /* if file not exist then create one */
        if (!destFile.exists()) {
            try {
                destFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        InputStream input1 = null;
        InputStream input2 = null;
        InputStream input3 = null;
        OutputStream output = null;
        InputStream input4 = null;

        try {

        /* FileInputStream to read streams */
            input1 = new FileInputStream(sourceFile1);
            input2 = new FileInputStream(sourceFile2);
            input3 = new FileInputStream(sourceFile3);

        /* FileOutputStream to write streams */
            output = new FileOutputStream(destFile, true);

            byte[] buf = new byte[1024];
            int bytesRead;
            output.write("{Record:[{".getBytes());
            while ((bytesRead = input1.read(buf)) > 0) {
                output.write(buf, 1, bytesRead);

                RandomAccessFile f = new RandomAccessFile(destFile, "rw");
                long length = f.length() - 2;
                f.setLength(length);
                length = f.length();
                f.close();
                output.write(",".getBytes());

            }

            while ((bytesRead = input2.read(buf)) > 0) {
                output.write(buf, 1, bytesRead);
                RandomAccessFile f = new RandomAccessFile(destFile, "rw");
                long length = f.length() - 2;
                f.setLength(length);
                length = f.length();
                f.close();
                output.write(",".getBytes());

            }

            while ((bytesRead = input3.read(buf)) > 0) {
                output.write(buf, 1, bytesRead);
                RandomAccessFile f = new RandomAccessFile(destFile, "rw");
                long length = f.length() - 2;
                f.setLength(length);
                length = f.length();
                f.close();
                output.write(",".getBytes());
                output.write(b.getBytes());
                output.write(d.getBytes());
                output.write("}]}".getBytes());

                output.write("\r\n".getBytes());

            }
        RandomAccessFile f1=new RandomAccessFile(destFile,"rw");
            long length1= f1.length()-1;
                f1.setLength(length1);
                f1.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                if (null != input1) {
                    input1.close();
                }

                if (null != input2) {
                    input2.close();
                }

                if (null != input3) {
                    input3.close();
                }

                if (null != output) {
                    output.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
Manu
  • 11
  • 6
  • This appends text to file but does not remove last character – Manu Apr 22 '18 at 17:25
  • How to append a json file after removing last charácter i.e "}" and add a ",".The text must be appended after comma. – Manu Apr 22 '18 at 17:27