title: Java Package Correction

text:
# Question
Title: Java Package Correction
I have a lot of java projects and I am often making new ones. I have a few helper classes (Vector, Logger, etc.) and it takes a lot of time correcting the first line to the correct package, I would really need a little program to help me fix it automatically.

Your program will first take the name of the package the files are moved to (eg. com.google.raycasting), after that each file with `****<FILENAME>****` between them. You read the input however you want (STDIN, program arguments, file, etc.).

When an EOF is reached, the program should output each file in the same way as in the input, but with the package declaration changed.

Example:

Input:

```
com.loovjo.tetris
****Vector.java****
package com.loovjo.someoldproject;
class Vector {
    public Vector (int x, int y) {
        System.out.println(x + ", " + y);
    }
}
****Logger.java****
package com.loovjo.someoldproject;
class Logger {
    public String name;
    public Logger(String name) {
        this.name = name;
    }
}

```

(Of course these aren't the real files.)

Output:

```
****Vector.java****
package com.loovjo.tetris;
class Vector {
    public Vector (int x, int y) {
        System.out.println(x + ", " + y);
    }
}
****Logger.java****
package com.loovjo.tetris;
class Vector {
    public Vector (int x, int y) {
        System.out.println(x + ", " + y);
    }
}

```

Further specification on Input/Output:

* The package declaration will not always be on the first line, the input may contain some newlines/spaces before it. If this is the case, those characters must be there in the output.
* The files in the input will always have correct syntax.

Remember, this is **Code Golf**, so the shortest code wins!

# Answer
> 1 votes
# Mathematica, 106 bytes

```
StringReplace[Rest@#~StringRiffle~"\n","package "~~__~~";"->"package "<>#[[1]]<>";"]&@StringSplit[#,"\n"]&

```

Works by splitting the string into its lines and returning all but the first line with any package declarations replaced with the new package.

# Answer
> 0 votes
# Java, 286 bytes

```
import java.util.*;class P{public static final void main(String[]a){Scanner s=new Scanner(System.in);for(String p="package "+s.nextLine(),e;(e=s.findWithinHorizon("(package[^;]+)|\"([^\"]|\\\\.)*\"|//.*|/\\*([^*]|\\*[^/])*|.|\n",0))!=null;System.out.print(s.match().start(1)>=0?p:e));}}

```

Take input from STDIN. Test case:

```
com.loovjo.tetris
****Foo.java****
    package something;
****Bar.java****
package
something.something
;
"package aaa;"
// package bbbb;
/**
 * package cccc;
 */
****Baz.java****
//comment:
package dddd;

```

Output:

```
****Foo.java****
    package com.loovjo.tetris;
****Bar.java****
package com.loovjo.tetris;
"package aaa;"
// package bbbb;
/**
 * package cccc;
 */
****Baz.java****
//comment:
package com.loovjo.tetris;

```

Cannot work with things like `package/*;*/stuff`, because regex.

---
Tags: code-golf, java
---