Swap two columns of a file in java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I am trying to write a method for swapping columns of a text file using java.
can someone show or tell me how to write a method to swap two columns of a file in java ? both columns are seperated by a space

One possible method:
Read in file and split data (see here reading tab delimited textfile java)
Overwrite file with same data read in, but column order switched.

Read every line of the file
ArrayList<String[]> aryL = new ArrayList<String[]>();
for each line of file
aryl.add(eachline.split(","));
for(String[] sArr: arrL)
//Swap the elements and print or write to file

you could read each line of a file and try
String buffer = "";
//for each line of input
String[] columns = line.split(" ");
buffer+= columns[1] + " " + columns[0] + "\n";
//end for
then overwrite the file with your buffer String

Related

Use of java.txt files, polymorphism and delimiters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I need to read from a text file in java and pass that information through a polymorphic method. My idea is a CryptoWallet in a .txt file reading as coin, amount and value, where in the text file its represented as Bitcoin 100 1.25.
Ive got the code reading from the file and printing it, as below.
public class CryptoCurrencies
public static void main (String[] args) throws IOException
{
System.out.println("Welcome to your Crypto Wallet"
+ "\nCurrently, you only own one coin.");
File CryptoWallet = new File("/Users/curti/OneDrive/Desktop/crypto.txt");
Scanner scan = new Scanner(CryptoWallet);
String fileContent = " ";
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
continue;
}
My main issue is actually getting the text file too recognise the numbers as doubles and variables, and assigning them to run through a polymorphic method. I understand the polymorphism side, but if anyone has any ideas for a possible polymorphic method id really appreciate it, having trouble thinking at the moment!
Thanks everyone.
It is unclear what role polymorphism is supposed to have here.
Assuming that each row represents a record and each record has the same form then we can parse each row in an identical fashion. That allows you to extract the numeric values using the parse methods in the appropriate Number classes.
For instance...
while(scan.hasNextLine()) {
String line = scan.nextLine());
String[] tokens = line.split(" ");
String name = tokens[0];
int amount = Integer.parse(tokens[1]);
double value = Double.parse(tokens[2]);
}
p.s. obligatory comment that you shouldn't represent money in floating point variables.
Split the current line by space or "\s+" regex, check if the length is 3, then use the double.parse function from the double object on the 2nd and 3rd element in the array.

Is it possible to find a word in a txt file and print the line as a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am stuck on some homework as i am new to java and still learning. I am wondering if it is possible to find a word in a .txt file and output the line that the word is on. I also need to allow a user to make a choice based on what is displayed back.
Example :
Word is Details
Txt file contains
Details on lion
Details on tiger
Output : "Details on tiger"
Thank in advanced for any help
This question has been answered before, but anyway You can go with this apporach.
Simply put:
Create a Scanner object and pass the required file into the
constructor as a new file object.
Iterate over the file with a
while loop until you find the specified string.
In order to store the lines that contains the desired word,we decalre a new string variable
Here's the code snippet:
Scanner scanner= new Scanner(new File("filename.txt"));
String lines = "";
while(scanner.hasNextLine()){
String stringLine = scanner.nextLine();
if(stringLine.indexOf("YOUR_WORD") != -1){
//print whatever you want here
System.out.println(stringLine);
//add every line that contains stringLine into another string;
lines+=stringLine;
}
}

how to split a text file by line gaps in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am reading a text file in Java that looks like this,
"
Q1. You are given a train data set having 1000 columns and 1 million rows. The data set is based on a classification problem. Your manager has asked you to reduce the dimension of this data so that model computation time can be reduced. Your machine has memory constraints. What would you do? (You are free to make practical assumptions.)
Q2. Is rotation necessary in PCA? If yes, Why? What will happen if you don’t rotate the components?
Q3. You are given a data set. The data set has missing values which spread along 1 standard deviation from the median. What percentage of data would remain unaffected? Why? "
Now, I want to read this file and then store each of these sentences(questions) in a string array. How can I do that in java?
I tried this,
String mlq = new String(Files.readAllBytes(Paths.get("MLques.txt")));
String[] mlq1=mlq.split("\n\n");
But this is not working.
Try this
String mlq = new String(Files.readAllBytes(Paths.get("MLQ.txt")));
String[] mlq1=mlq.split("\r\n\r\n");
System.out.println(mlq1.length);
System.out.println(Arrays.toString(mlq1));
This should do it by line gap of 2 lines.
File file = new File("C:\\MLques.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st + "\n");
}
I think it will work.
This is a piece of code from one of my project.
public static List<String> readStreamByLines(InputStream in) throws IOException {
return IOUtils.readLines(in, StandardCharsets.UTF_8).stream()
.map(String::trim)
.collect(Collectors.toList());
}
But!!! If you have really big file, then collecting all content into a List is not good. You have to read InputStream line by line and do all you need for every single row.

How to write a String to fixed-size text files in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have a very long string and I want to write it to several text files of fixed size. For example, I want to set the size to be 1MB per file, and label each file as "text01.txt", "text02.txt"...
How can I achieve this in the simplest way?
Keep track of the number of bytes you're writing, and when it reaches a specified point, close the existing file and continue in a new one. There's no need to analyze the size of the file, since you know exactly what's going into it.
Something like this:
long fileSizeByteLimit = 5000000;
long bytesOutput = 0;
while(THEREAREMORELINESTOOUTPUT) {
//Open a new file
while(bytesOutput <= fileSizeByteLimit) {
writer.append(lineOfOutput);
bytesOutput += lineOfOutput.length();
}
//Close file
}

characters display of a text file in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a text file which contains a line as a,b,a,b,a,b and I want to display the line as b,b,b,a,a,a
any assistance would be appreciated
Use BufferedReader's readLine() method to read a line from the file.
Use String's split() to split the line into tokens (characters in this case).
Sort the array returned from String.split() using Arrays.sort() (note that the order will be the opposite to that required so you should reverse through the array when printing), or store the array into an ArrayList and use Collections.sort() and specify your own Comparator.
public static void main( String[] args) {
String line="a,b,a,b,a,b";
String[] split = line.split( "," );
Arrays.sort( split );
for ( int i = split.length -1; i > 0 ; i--) {
System.out.print( split[i] );
System.out.print( "," );
}
System.out.print( split[0] );
}
Split the text based on ','
Just create an array and keep storing elements on that array , sort this array whatever way you want to , and the print the output
Let's break it into steps:
Open the file
Read the line from the file
Parse the line into individual elements
Add the elements to a data structure
Sort the data structure
Reverse the order
Display the data structure, either by rendering the contents or creating a String
Which part are you having trouble with?

Categories