Trying to write a string to a text file, which works, but doesn't include the newline \n part. Can someone tell me why it won't work? \t works fine but this just wont.
FileReader class:
import java.io.*;
public class FileReader
{
public static void readFile()
{
try
{
PrintWriter f;
File file = new File("../webapps/Assignment1/Seats.txt");
if(!file.exists())
{
f = new PrintWriter(file);
f.write(populateSeats());
f.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static String populateSeats()
{
String rowID[] = {"A", "B", "C" ,"D" ,"E" ,"F" ,"G" ,"H"};
String seatPop = "";
int rowCount = 0;
int colCount = 1;
for(int r = 0; r < 8; r++)
{
for(int c = 0; c < 8; c++)
{
seatPop += "SeatID: " + rowID[rowCount] + colCount + "\n";
seatPop += "Avail: True \n";
seatPop += "UserID: null\n";
seatPop += "Phone: null\n";
seatPop += "Address: null\n";
seatPop += "Email: null\n";
colCount++;
}
colCount = 1;
rowCount++;
}
return seatPop;
}
}
Main class (Just makes an instance of FileReader and then run the method)
FileReader file = new FileReader();
file.readFile();
I speculate that the \n are in fact being written to the file, but that the system you are using does not use \n as the line separator. If so, then these characters would be present, be they might be getting rendered as newlines in your editor. Instead, try using a system independent line separator:
System.lineSeparator(); // Java 7 or later; I'll assume this is your case
In your code you might do this:
for (int c = 0; c < 8; c++) {
seatPop += "SeatID: " + rowID[rowCount] + colCount + System.lineSeparator();
// etc.
}
When adding a new line for files on windows use \r\n instead of \n.
\n was made specificly for Unix / Linux Systems.
\r\n will add a new line when being used on windows.
So in your code change it to
for (int c = 0; c < 8; c++) {
seatPop += "SeatID: " + rowID[rowCount] + colCount + "\r\n";
// .....
}
However as Tim said in his answer above, the best way would be to use the System.lineSeparator(); method as this will return the proper escape sequence to generate a new line independent of the operating system. As such I would reccomend you use System.lineSeparator(); over \r\n.
Related
I need to use MATLAB/Octave with ProcessBuilder class in Java. I have one argument and it going to be a very very long string that are shaped as a MATLAB/Octave array.
[1 2 3 4;
4 5 6 3;
.
.
.
3 4 2 5]
So I begun to code where A is the matrix and matA is going to be the argument in ProcessBuilder object.
String matA = "[";
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
matA = matA + " " + A[i][j];
}
if(i < rows-1)
matA = matA + ";";
}
matA = matA + "]";
System.out.println(matA);
Like this:
ProcessBuilder processBuilder = new ProcessBuilder(matA);
processBuilder.command("singularvaluesdecomposition.m");
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And my MATLAB/Octave file looks like this:
function singularvaluesdecomposition(A)
[U, S, ~] = svd(A);
U
diag(S)
end
But building matA takes enormus amout of time. Is there any faster whay todo this?
when changing data a lot, it is better to use StringBuilder instead of String.
Strings are immutable and changing them is done by making another object, though the user can't see that visually.
try this:
StringBuilder matA = new StringBuilder("[");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
matA.append(" " + A[i][j]);
}
if(i < rows-1)
matA.append(";");
}
matA.append("]");
System.out.println(matA);
for more info:
https://javapapers.com/java/java-string-vs-stringbuilder-vs-stringbuffer-concatenation-performance-micro-benchmark/
The problem is reading back an r,g,b and setting the r,g,b into a setBackground colour when reading from a csv file (comma separated values file) but the csv file also has text in it that needs to be set to the text fields.
the save button saves the file into a csv format that then needs to be read back into the fields which is just a 2d array of text fields.
public void writeDataFile(String fileName)
{
try
{
BufferedWriter outFile = new BufferedWriter(new FileWriter("e:\\EmissionsTracker.csv"));
for (int x = 0; x < totalX; x++)
{
for (int y = 0; y < totalY ; y++)
{
outFile.write(fields[0][y].getText() + "," + fields[x][0].getText() + "," + fields[x][y].getText() + ",");
outFile.write(fields[x][y].getBackground() + ",");
outFile.newLine();
}
}
outFile.close();
}
public void saveEmmisionsTableToFile(String fileName)
{
try
{
BufferedWriter outFile = new BufferedWriter(new FileWriter(fileName));
for (int y = 0; y < totalY; y++)
{
for (int x = 0; x < totalX; x++)
{
outFile.write(fields[x][y].getBackground() + "," );
}
outFile.newLine();
}
outFile.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
private void readDataFile(String fileName)
{
try
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
for (int x = 0; x < totalX; x++)
{
for (int y = 0; y < totalY; y++)
{
String temp[] = br.readLine().split(",");
fields[x][y].setText(temp[5]);
}
}
br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
for (int x = 0; x < totalX; x++)
{
for (int y = 0; y < totalY ; y++)
{
outFile.write(fields[0][y].getText() + "," + fields[x][0].getText() + "," + fields[x][y].getText() + ",");
outFile.write(fields[x][y].getBackground().getRed() + "," + fields[x][y].getBackground().getGreen() + "," + fields[x][y].getBackground().getBlue() + ",");
outFile.newLine();
}
}
for (int x = 0; x < totalX; x++)
{
for (int y = 0; y < totalY; y++)
{
String temp[] = br.readLine().split(",");
fields[x][y].setText(temp[2]);
fields[x][y].setBackground(new Color(Integer.parseInt(temp[3]),Integer.parseInt(temp[4]),Integer.parseInt(temp[5])));
}
}
CSV files that contain commas in their values should start and end with double quotes. This statement from RFC 4180 summarises it well:
Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes. For example:
"aaa","b CRLF
bb","ccc" CRLF
zzz,yyy,xxx
Any half-decent CSV parsing library will take care of this for you automatically.
See also So You Want To Write Your Own CSV code? and these two questions which contain Java CSV library recommendations
So I'm working on a project for school. I need to record the data from my arrays into Excel and I'm having some trouble. This is part of my experiment class.
public static void exp(Params params) {
Scanner s = new Scanner(System.in);
String temp;
for (temp = ""; temp.isEmpty(); temp = s.nextLine()) {
System.out.println("Enter a directory and filename that you want the results to be saved under.");
System.out.println("(If no directory is specified, results will be in same folder as the jar.)");
}
params.setFileName(temp);
s.close();
System.out.println("Executing...");
long timeArray[] = new long[params.getFinalSize() / params.getIncrement()];
int counter = 0;
SortFacade facade = new SortFacade();
for (int n = params.getInitialSize(); n <= params.getFinalSize(); n += params.getIncrement()) {
System.out.println((new StringBuilder("Array of size: ")).append(n).toString());
long tempTime = 0L;
for (int j = 0; j < params.getNumTrials(); j++) {
System.out.println((new StringBuilder("Trial #")).append(j + 1).toString());
params.generateArrays(n, params.getTypeList());
tempTime += facade.sort(params);
}
timeArray[counter] = tempTime / (long) params.getNumTrials();
counter++;
}
params.setTimeArray(timeArray);
System.out.println("Times for each array size(ms): " + Arrays.toString(timeArray));
System.out.println("Writing to File...");
System.out.println("Complete.");
}
}
Start with Filewriter
Make sure what you write is comma-delimeted and saved as a .csv
Also, take a look at this existing question.
I have this function to check if some words appear in a specific line, and then surround them with a given char.
The code above works like a charm, however since the words in the string array "words" are always low case, the words will be lower case as well. How can i fix this issue ?
The inputs:
BufferedReader in = "Hello, my name is John:";
char c = '*';
String [] words = {"hello","john"};
The desired output:
BufferedWriter out = "*Hello*, my name is *John*:";
The actual output:
BufferedWriter out = "*hello*, my name is *john*";
The code:
public void replaceString(BufferedReader in, BufferedWriter out, char c, String[] words){
String line_in = in.readLine();
while (line_in != null) {
for (int j = 0; j < words.length; j++) {
line_in = line_in.replaceAll("(?i)" + words[j], bold + words[j]
+ bold);
}
out.write(line_in);
out.newLine();
line_in = in.readLine();
}
}
Use
line_in.replaceAll("(?i)(" + words[j] + ")", bold + "$1" + bold);
// \________________/ \/
// capture word reference it
Following code block works fine in dev mode but when I deploy to server it does not.Could not split the multi line with new line characters?
Basically, Format the multi-line string as "," separated string tokens.
packages:
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.regexp.shared.SplitResult;
public void onSubmitComplete(SubmitCompleteEvent event) {
String plateStr = "";
if(event.getResults() != null){
String uploadStr = event.getResults();
//Log.warn(this.getClass().getName() + " - event.getResults():"+ uploadStr);
RegExp regExp = RegExp.compile("\\r?\\n");
SplitResult sp = regExp.split(uploadStr);
Log.warn(this.getClass().getName() + " - sp.length():"+ sp.length() + ", SplitResult:"+ sp.toString());
for(int i = 0; i < sp.length() ; i++){
Log.warn(this.getClass().getName() + " - PlateLine["+ i+ "] - " + sp.get(i));
if(!sp.get(i).trim().isEmpty()){
RegExp regLine = RegExp.compile(",");
SplitResult spLine = regLine.split(sp.get(i));
for(int j = 0; j < spLine.length(); j++){
if(spLine.get(j) != null && !spLine.get(j).trim().isEmpty()){
plateStr = plateStr + "," + spLine.get(j);
}
}
}
}
//plateStr = Arrays.toString(lines).replace("[","").replace("]", "");
if(!plateStr.trim().isEmpty()){
plateStr = plateStr.substring(1,plateStr.length());
}
Log.warn(this.getClass().getName() + " - PlateString:"+ plateStr);
}
I tried following workaround with java script native query but it also doesn't work.
JsArrayString arrayString = splitString(uploadStr, "\n");
public static final native JsArrayString splitString(String string, String separator) /*-{
return string.split(separator);
}-*/;
REF:
GWT JSNI split method bug