Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, March 8, 2024

Easy Way To Create HTML/XML String

A simple way to create html tags in Java.

It won't create a tree that you can parse, but it will create the text needed. You see we'll use the StringBuilder class along with the Formatter class to accomplish this. This provides a simple way to format a string without using String.format inside of a sb.append call.

import java.util.Formatter;
import java.util.Locale;

public class LocalMe {
    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb, Locale.ENGLISH);
        formatter.format("<%s>%s</%s>", "greeting", "Hello World", "greeting");
        System.out.println(formatter.toString());

    }
}

Thursday, March 7, 2024

Get Yesterday's Date

Here's an easy method to return yesterday's date:

import java.time.LocalDateTime;

public class DoIt {

    public static void main(String[] args) {
        LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
        System.out.println(yesterday);
    }
}

As you can see it's quite straight forward and simple. You just minus the number of days you wish to get. You can do this on a LocalDate or a LocalDateTime object.

From there you can do whatever you want with your past date.



Sunday, February 18, 2024

CommandLine Arguments

Here's an interesting way to check for commandline arguments. First we setup an enum that holds our commands. As you can see, I can pass in either -h or -helpK into my program. To do this we convert the values for a specific command into a HashSet and then compare the values to what was passed in. If what we passed in is in the HashSet then we return a true vlaue, otherwise we return a false value.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public enum Commands {

    HELP("-h,-help");

    private final String values;
    Commands(String values) {
        this.values = values;
    }

    public String getValues() {
        return this.values;
    }

    public Set<String> getValuesAsArray() {
        return new HashSet<>(Arrays.asList(this.getValues().split(",")));
    }

    public boolean isSelected(String[] args) {
        for (String arg : args) {
            if (getValuesAsArray().contains(arg)) {
                return true;
            }
        }
        return false;
    }
}

In our main method of the program, we can check for values like this:

public class Main {

    public static void main(String[] args) {
        if (Commands.HELP.isSelected(args)) {
            System.out.println("Help");
        }
    }
}

At which point we perform whatever code we need to perform on it. There is a way to pass in parameters to the arguments that we are passing to the program too. But that's another story altogether.

I'm not saying this is the perfect or correct way of doing this, but it is a way of doing this for sure.

Game Loop

 Found this gameloop somewhere, probably on the internet of course. Maybe YouTube? I can't remember. Putting it here so I can use it later:


long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while(running){
	long now = System.nanoTime();
	delta += (now - lastTime) / ns;
	lastTime = now;
	while(delta >= 1){
		tick();
		updates++;
		delta--;
	}
	render();
	frames++;
			
	if(System.currentTimeMillis() - timer > 1000){
		timer += 1000;
		System.out.println("FPS: " + frames + " TICKS: " + updates);
		frames = 0;
		updates = 0;
	}
}

Wednesday, February 7, 2024

Change Created Date of a File

Sometimes you want to be able to change the created date of a file. Don't ask me WHY you would ever need to do this, but well here's a way in Java.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.*;

public class ChangeCreatedDate {

    public static void main(String[] args) throws IOException {
        if (args.length == 2) {
            File file = new File(args[0]);
            if (file.exists()) {
                file.setLastModified(System.currentTimeMillis());
            } else {
                file.createNewFile();
            }
        }

        LocalDate date = LocalDate.parse(args[1]);
        LocalTime time = LocalTime.now();
        Path file = Paths.get(args[0]);
        FileTime fileTime = FileTime.fromMillis(getMillisecondsSince1970(date, time));
        Files.setAttribute(file, "creationTime", fileTime);
    }

    public static long getMillisecondsSince1970(LocalDate date, LocalTime time) {
        ZonedDateTime zonedDateTime = ZonedDateTime.of(
                date,
                time,
                ZoneId.systemDefault());
        return zonedDateTime.toInstant().toEpochMilli();
    }
}

Looking back at it, I wonder why I didn't make it so you could update the time as well as the date. Interesting. I mean it would make sense to be able to update both the date AND time. But I didn't have that in this section of code. Oh well, I'm sure I'll change it someday.

I find it interesting that we're updating an attribute of the file. One would think it would be someplace else, or easier to access directly on the file object itself. But well, it's not. So that's just that.

Tuesday, February 6, 2024

Return The File Extension of a File

So this little method will return the file extension of a file. That is, it will look for the dot (.) in a filename and return the remaining characters after it.

Notice that it makes sure it's a file and not a directory.

/**
     * Returns the extension of a file
     *
     * @param filename the name of the file
     * @return the extension of the filename
     */
    public static String getExtension(String filename) {
        String ext = null;

        File file = new File(filename);
        if (file.exists() && file.isFile()) {
            ext = filename.substring(filename.lastIndexOf(".") + 1);
        }

        return ext;
    }

Pretty simple no? Yeah that's what I was thinking.

You can easily put this in a FileUtils class that you might be building. It could come in handy.

Please remember that the file extension does not dictate what the file type is. It's just an extension.

Backing Up A File

 Backing up a file in Java can be fairly simple and straight forward. Let's think about it for a second. You have a file.

  1. You want to be able to store a copy of that file somewhere on your file system.
  2. You either want to keep the original or delete the original.
  3. The format of the filename must be unique, so it doesn't collide with other backed up files.
There are just a few considerations to think about. Here's a solution I came up with in Java:


import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.File;
import java.util.Date;
import java.text.SimpleDateFormat;

public class Backup {

    public static void main(String[] args) {
        if (args.length == 1) {
            File file = new File(args[0]);

            if (file.exists()) {
                try {
                    File dir = new File("archive");
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    Date date = new Date();
                    SimpleDateFormat dt = new SimpleDateFormat("'.'yyyy-MM-dd-HH-mm-ss");
                    Path source = Paths.get(args[0]);
                    Path target = Paths.get(dir.getName(), file.getName() + dt.format(date));

                    System.out.println("Backing up file: " + source + " --> " + target);

                    Files.copy(source, target);
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.err.println("The file you specified '" + file.getName() + "' doesn't exist.");
            }
        }
    }
}

As you can see I chose to delete the file at the end of the process. But let's take a look at what this does:

  1. We make sure at least one filenamne is passed in and if it exists we continue.
  2. We create a home for the archived file, in this example we call it archive.
  3. We create a date and format it.
  4. We set a source and a target and output that we are copying the source to the target.
  5. Using Files.copy we do the actual backup.
  6. Then we delete the file at the end of the process.

That's all there is to it. I'm sure there could be a way to refactor this so it's better somehow. I'll have to look into it.

Monday, February 5, 2024

Clear Screen

Sometimes when you're writing a program in Java you want to clear the screen. That is to remove all text from the screen.

Here's how we would do this in Java:

private void clearScreen() {
        try {
            if (System.getProperty("os.name").contains("Windows")) {
                new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
            } else {
                new ProcessBuilder("clear").inheritIO().start().waitFor();
            }
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
    }

This takes into account both windows and non windows. cls for Windows, clear for linux etc.

Sunday, February 4, 2024

Determine if a number is Odd or Even

Sometimes you want to be able to check if a number is odd or even. Here's a simple method that will do just that.

public class OddOrEven {

  public static void main(String[] args) {
    int i = Integer.valueOf(args[0]);
    System.out.println(oddOrEven(i));
  }

  public static String oddOrEven(int number) {
    if (number %2 == 0) {
      return "Even";
    } else {
      return "Odd";
    }
  }
}

Naturally you'll want to do some value checking for the number input at the command line. It could easily throw an InvalidNumberFormat exception. I think that's the exception that would be thrown.

Other kinds of Argument checking

So we've talked about a possible argument checking in Java. What if you just want to pass in files to be worked on?

That's simple enough, just loop through your argument array and perform the work on the files in question. Here's a simple way of doing that.

public static void main(String[] args) {
    for (String arg : args) {
    	doSomethingSpecial(arg);
    }
}

You can easily save the results back out to the same file as well since you will have that current argument in your posession. Easy right? Yeah something like that.

What if you want to perform an action based if an argument is passed in?

Let's say that you pass the filename as the first argument, then you pass the operations you wish to perform on that argument in the following arguments.

You can easily get the first argument by doing args[0], and then you can put the remaining arguments in a HashSet and check one by one if the specified argument is there. If it is, then perform the specified operation on it that you define in your codebase. Let me see if I have an example of this:

public static void main(String[] args) {
        Set arguments = new HashSet<>(Arrays.asList(args));
        if (arguments.contains("doit")) {
            System.out.println("Doing it!");
        }
    }

Yep I did have an example. How's that for something? It all works out in the end. You can of course modify the code based upon whatever circumstance you need to work with.

Saturday, February 3, 2024

Command line Arguments in Java

I found the code I was looking for:

static class Args {

    public static Map<String, List<String>> parseArgs(String[] args, Set<String> validArgs) {
        Map<String, List<String>> map = new HashMap<>();

        List<String> options = null;

        for (String a : args) {
            if (a.charAt(0) == '-') {
                if (a.length() < 2) {
                    throw new IllegalArgumentException("Invalid Argument: " + a);
                }
                if (!validArgs.contains(a)) {
                    throw new IllegalArgumentException("Invalid Argument: " + a);
                }
                options = new ArrayList<>();
                map.put(a, options);
            } else if (options != null) {
                options.add(a);
            } else {
                throw new IllegalArgumentException("Invalid Argument: " + a);
            }
        }
        return map;
    }
}

I've modified this piece of code then was in the original post. You can pass this a Set of Strings that ensure only the correct proper argumetns are being passed into the program as to not waste the programs time trying to decide if they are proper later.

Hello World!

Sometimes you just want to say hello! This is how we say hello in Java.


public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Monday, November 1, 2021

LocalDate

To set a LocalDate with today's date we can use the following:


LocalDate.of(2021, 10, 30)

The above allows us to set a date, any date. There's another way to set a date using LocalDate.


LocalDateTime ldt = LocalDateTime.now();

Sunday, October 31, 2021

JList Populated From String Array


import javax.swing.JFrame;
import javax.swing.JList;

public class ListTest {

public ListTest() {
JFrame frame = new JFrame();
frame.setTitle("JList Test");
frame.setSize(640,480);
frame.setLocationRelativeTo(null);

String[] items = {"One", "Two", "Three"};
JList list = new JList(items);

frame.add(list);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {
new ListTest();
}
}

Friday, October 29, 2021

Multiplication Table in Java

Nested for loops.


for (int i = 1; i <=12; i++) {
for (int j = 1; j <= 12; j++) {
System.out.printf("%d * %d = %d\n", i, j, i*j);
}
}

Wednesday, October 27, 2021

Netbeans

Been playing around with Netbeans lately. It's an okay tool. I enjoy the form creator the most in it. It's easy to create a form and then display whatever it is you wanted to create. I made a handy dandy food calorie tracker using this method.

All in all it's not bad. The code it creates is ugly as hell, but that's okay for small simple projects that I don't want to think about creating a form for manually.

Monday, October 25, 2021

Source Code for Simple Database Program

This database program is simple, it uses the sqlite jar for connecting to the SQLite database.

It can store a file's text in a database, update that text, and extract that text back out to it's original file name.

It's pretty quick and dirty. There might be better ways to handle some of it, but I just wanted to make sure it would do what I wanted it to do.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Sample {

private Connection conn = null;

public Sample() {

}

public void init() {

try {
String url = "jdbc:sqlite:sample.db";
conn = DriverManager.getConnection(url);

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

public void saveData(String filename) {
try {
String fileContent = new String(Files.readAllBytes(Paths.get(filename)));
String sql = "insert into files(name, content) values(?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, filename);
pstmt.setString(2, fileContent);
pstmt.executeUpdate();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

public void updateData(String filename) {
try {
String fileContent = new String(Files.readAllBytes(Paths.get(filename)));
String sql = "update files set content = ? where name = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, fileContent);
pstmt.setString(2, filename);
pstmt.executeUpdate();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

public void exportData(String id) {
StringBuilder sb = new StringBuilder();
String sql = "select * from files where id = ?";
ResultSet rs = null;
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, id);
rs = pst.executeQuery();

while (rs.next()) {
Path path = Paths.get(rs.getString("name"));
Files.writeString(path, rs.getString("content"), StandardCharsets.UTF_8);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
if (args.length != 2) {
System.err.println("ERROR: You must provide two arguments.");
System.err.println("insert or update");
System.err.println("filename to insert or update");
return;
}
Sample sample = new Sample();
sample.init();
if (args[0].equals("insert")) {
sample.saveData(args[1]);
} else if (args[0].equals("update")) {
sample.updateData(args[1]);
} else if (args[0].equals("export")) {
sample.exportData(args[1]);
}

}
}

Friday, October 22, 2021

Formatting a Date in Java

For some reason my installation of Java wouldn't let me use SimpleDateFormat to format my dates. So I had to google a different way to do this and found the following works as well. The Date class has a bunch of issues with it to begin with, so this is much cleaner and better as well.


LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.ENGLISH);
String formattedString = df.format(ldt);

Populate JTable from ResultSet

Every once in a while we need to populate data in a JTable. Here's a simple to use DefaultTableModel for populating a JTable from a ResultSet.


public DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {

ResultSetMetaData metaData = rs.getMetaData();

Vector columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}

Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}

DefaultTableModel dtm = new DefaultTableModel(data, columnNames) {

private static final long serialVersionUID = 1L;

@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};

return dtm;

}

Thursday, October 21, 2021

Connect to a SQLite Database in Java

Sometimes you need to connect to a database. Here is some code that will allow you to connect to an SQLite database using Java.


public static Connection connect() {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:sqlite:sample.db");
} catch (SQLException sqle) {
sqle.printStackTrace();
Logger.getLogger(SQLite.class.getName()).log(Level.SEVERE, null, sqle);
}
return conn;
}

Slump

 I feel like I'm in a slump. I can't even think of what to write about. The cursor just sits there. It's a staring match that wo...