I have following code. On making changes in the text file when I open the file I can't see any change in fact the text of text file is removed.
private void btnGo_Click(object sender, EventArgs e)
{
string content;
string newword = "Tanu";
string oldword = "Sunrise";
System.IO.StreamReader file =
new System.IO.StreamReader(txtFilePath.Text);
while ((content = file.ReadLine()) != null)
{
if (content == "Project name = Sunrise ")
{
string newtxt = Regex.Replace(content, oldword, newword);
content = content.Replace(content, newtxt);
}
// counter++;
}
file.Close();
using (StreamWriter writer = new StreamWriter(txtFilePath.Text))
{
writer.Write(content);
writer.Close();
Error is in your while loop.
while ((content = file.ReadLine()) != null)
after replacing content with newtxt while is executing again and is trying to read next line in file which is setting content to null and so when you come out of while loop your content is null.
try reading file content into a different variable or use say newtxt itself to write to file.
Related
I was trying to create a feature to create hyperlinks in the console while the information is added.
While debugging, I noticed that the first hyperlink is succesfully created, but when the next line is printed to console, the hyperlink dissapears.
The code which I use to create the hyperlinks is:
String hyperLinkText = "test";
myConsole.printToConsole(test);
String myFile = new File("D:/Test/testFile.txt");
URI location = myFile.toURI();
IFile[] files = project.getWorkspace().getRoot().findFilesForLocationURI(location);
HyperlinkInformation hyperlinkInformation = new HyperlinkInformation(myConsole, myConsole.getDocument().get().length(), hyperLinkText.length());
FileHyperlink fileHyperlink = new FileHyperlink(hyperlinkInformation,
files[0], 1);
try {
hyperlinkInformation.getConsole().addHyperlink(fileHyperlink,
fileHyperlink.getOffset(), fileHyperlink.getLength());
} catch (BadLocationException e) {
//
}
The function addHyperlink:
public void addHyperlink(IHyperlink hyperlink, int offset, int length) throws BadLocationException {
IDocument document = getDocument();
ConsoleHyperlinkPosition hyperlinkPosition = new ConsoleHyperlinkPosition(hyperlink, offset, length);
try {
document.addPosition(ConsoleHyperlinkPosition.HYPER_LINK_CATEGORY, hyperlinkPosition);
fConsoleManager.refresh(this);
} catch (BadPositionCategoryException e) {
ConsolePlugin.log(e);
}
}
Is this the normal behaviour or am I missing something?
The Problem:
On my Windows file server I have around 1,000,000 SolidWorks files that have metadata in the file properties under a custom tab (see image below) that I would like to export to a single CSV file.
These files are located in sub-tree of folders, and mixed with other file types.
The Solution:
A script is needed to only target specific file types (extensions) in a sub-tree of folders, that exports the metadata from the custom tab to a CSV File, where i can then clean up and import the data into an SQL database.
I am not sure the best way to achieve this I was thinking along the lines of PowerShell, any help to get going would be greatly appreciated.
If you use a .NET language like C# or Visual Basic, you can use the SolidWorks API and the Document Manager libraries (you'll need to get a license, free with your subscription from the Customer Portal) to extract this information without opening the files. It's quite fast. As for only looking at certain files, that's straight forward with .NET IO.Path.GetExtension.
Below is a working example of what I think you're looking for.
You will need the Document Manager dll, which is on the SolidWorks API SDK, which is included in the installation media. Then you can referencene SolidWorks.Interop.swdocumentmgr.dll.
You will also need a Document Manager Serial Number which you can request through the SolidWorks Customer Portal free of charge with your SolidWorks Subscription. Once you have that number, replace the lic string value below with the entire serial number, in quotes.
To define which Custom Properties to read from the SolidWorks files, just change the list propertiesToRead to include any values you need to retrieve. These are NOT case sensitive.
You you run this, you will be prompted to enter a directory path. This is also where the Output.csv file will be created.
At the bottom is a screen-shot of sample results.
using SolidWorks.Interop.swdocumentmgr;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace WriteProperties
{
class Program
{
static ISwDMApplication4 docManager;
static List<string> propertiesToRead = new List<string>() { "Number", "Description", "Revision", "Material", "Finish", "Weight" };
const string lic = "YOU CAN GET THIS NUMBER FROM THE CUSTOMER PORTAL WITH YOUR SOLIDWORKS SUBSCRIPTION AT NO COST";
static char[] charactersToQuote = { ',', '"', '\n' };
const string QUOTE = "\"";
const string QUOTEFORMATTED = "\"\"";
static void Main(string[] args)
{
string directoryPath = GetDirectory(args);
if (string.IsNullOrEmpty(directoryPath)) return;
if (!LoadDocManager()) return;
string outputPath = Path.Combine(directoryPath, "Output.csv");
StringBuilder sb = new StringBuilder();
sb.AppendLine("File Name," + string.Join(",", propertiesToRead));
int counter = 0;
foreach (string filePath in Directory.EnumerateFiles(directoryPath, "*.sld*", SearchOption.AllDirectories))
{
SwDMDocument21 dmDocument = GetDocument(filePath);
if (dmDocument == null) continue;
WriteProperties(sb, dmDocument, filePath);
counter++;
}
File.WriteAllText(outputPath, sb.ToString());
Console.WriteLine("{0} files read and saved to {1}", counter, outputPath);
Console.ReadLine();
}
static string GetDirectory(string[] args)
{
if (args != null && args.Count() > 0 && Directory.Exists(args[0])) return args[0];
Console.WriteLine("Directory to read:");
string filePath = Console.ReadLine();
if (Directory.Exists(filePath)) return filePath;
Console.WriteLine("Directory does not exists: {0}", filePath);
return string.Empty;
}
static bool LoadDocManager()
{
if (docManager != null) return true;
try
{
SwDMClassFactory factory = new SwDMClassFactory();
if (factory == null) throw new NullReferenceException(nameof(SwDMClassFactory));
docManager = (SwDMApplication4)factory.GetApplication(lic);
if (docManager == null) throw new NullReferenceException(nameof(SwDMApplication4));
return true;
}
catch (Exception ex)
{
Console.WriteLine("Document Manager failed to load: {0}", ex.Message);
Console.ReadLine();
return false;
}
}
static SwDMDocument21 GetDocument(string filePath)
{
SwDmDocumentType documentType = GetDocType(filePath);
if (documentType == SwDmDocumentType.swDmDocumentUnknown) return null;
SwDmDocumentOpenError result = SwDmDocumentOpenError.swDmDocumentOpenErrorNone;
SwDMDocument21 dmDocument = (SwDMDocument21)docManager.GetDocument(filePath, documentType, true, out result);
if (result == SwDmDocumentOpenError.swDmDocumentOpenErrorNone || result == SwDmDocumentOpenError.swDmDocumentOpenErrorFileReadOnly) return dmDocument;
if (dmDocument != null) dmDocument.CloseDoc();
return null;
}
static SwDmDocumentType GetDocType(string filePath)
{
if (filePath.Contains("~$")) return SwDmDocumentType.swDmDocumentUnknown;
switch (Path.GetExtension(filePath).ToLower())
{
case ".sldprt": return SwDmDocumentType.swDmDocumentPart;
case ".sldasm": return SwDmDocumentType.swDmDocumentAssembly;
case ".slddrw": return SwDmDocumentType.swDmDocumentDrawing;
default: return SwDmDocumentType.swDmDocumentUnknown;
}
}
static void WriteProperties(StringBuilder sb, SwDMDocument21 dmDocument, string filePath)
{
Console.WriteLine("Reading {0}", filePath);
List<string> propertiesInFile = new List<string>();
if (dmDocument.GetCustomPropertyCount() > 0) propertiesInFile.AddRange(dmDocument.GetCustomPropertyNames());
string csvLine = filePath;
foreach (string property in propertiesToRead)
{
string propertyValue = "";
if (propertiesInFile.Any(s => string.Compare(s, property, true) == 0))
{
SwDmCustomInfoType propertyType = SwDmCustomInfoType.swDmCustomInfoText;
string resolvedValue;
propertyValue = dmDocument.GetCustomPropertyValues(property, out propertyType, out resolvedValue);
}
csvLine = csvLine + "," + FixChars(propertyValue);
}
sb.AppendLine(csvLine);
dmDocument.CloseDoc();
}
static string FixChars(string s)
{
if (s.Contains(QUOTE)) s = s.Replace(QUOTE, QUOTEFORMATTED);
if (s.IndexOfAny(charactersToQuote) > -1) s = QUOTE + s + QUOTE;
return s;
}
}
}
Here is a sample output
I'm having some trouble locating the text file in my code
public static void main(String[] args) {
if (args.length != 2) {
throw new IllegalArgumentException("args is out of range");
}
final String from = args[0];
final String to = args[1];
int errCode = 0; // Unix error handling
// FileReader uses "the default character encoding".
// To specify an encoding, use this code instead:
// new BufferedReader(new InputStreamReader(new
// FileInputStream(fileName), "UTF-8"));
// This "try-with-resource" statement automatically calls file.close()
// just before leaving the try block.
try (BufferedReader file = new BufferedReader(new FileReader("distances.txt"))) { // absolutadressen :C
pathSearch(from, to, file);
} catch (IOException e) {
System.err.println("File not found");
errCode = 1;
} finally {
System.exit(errCode);
}
}
Everytime I run it, it says "File not found". I've tried replacing "distances.txt" with the adress distances.txt is at. distances.txt is also inside the project folder so I don't understand why it's not being found. If i run the code from the terminal, the file can be found by using its adress, but I would like it to work from eclipse. An alternativ is to be able to place this whole package
Here's a pic of the project
Take it out of the package to the src folder, then use the line below to read it:
BufferedReader file = new BufferedReader(new FileReader(getClass().getResource("/distances.txt").getFile()));
I have a file on the SDcard - "file.txt" containing telephone numbers in separate line.
I want to display line first, and then if I press a button, the second line should be displayed in the TextView and the first line should disappear.
I have code that simply reads the contents of txt file and fully insert all rows in TextView:
How should I change this code to the serial output the following line when you press the button????
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"file.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
tv.setText(text);
How should I change this code to the serial output the following line when you press the button????
You could store the content of the file in ArrayList< String> , and then, upon pressing a button, change the text in your TextView to another in the list. Something like:
Reading file and storing in a list:
//make this a class member variable
List<String> numbers = new ArrayList<String>();
while((line = br.readLine()) != null) {
//store each line in our list as separate entry
numbers.add(line);
}
Updating TextView upon button press:
//make this a class member variable
//this is being used to get the line from list
int currentLine = 0;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the text
tv.setText(numbers.get(currentLine));
//increment currentLine
currentLine++;
//make sure we don't go beyond the number of lines stored in the list
//so if we reach the last index, we start from the beginning
if (currentLine == numbers.size()) {
currentLine = 0;
}
}
});
I have a rest service written to receive a file and save it.
The problem is that when I receive more than 2 requests, the files are not written only the last request is taken into consideration and written.
Here is my code:
#POST
#RequestMapping(value = "/media/{mediaName}/{mediaType}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#ResponseBody
public String updateResourceLocally(#FormDataParam("rawData") InputStream rawData, #PathVariable("mediaName") String mediaName, #PathVariable("mediaType") String mediaType) {
logger.info("Entering updateResourceLocally for " + jobId + "; for media type: " + mediaType);
final String storeDir = "/tmp/test/" + mediaName + ("/");
final String finalExtension = mediaType;
final InputStream finalRawData = rawData;
// new Thread(new Runnable() {
// public void run() {
// writeToFile(finalRawData, storeDir, finalExtension);
// }
// }).start();
writeToFile(finalRawData, storeDir, finalExtension);
// int poolSize = 100;
// ExecutorService executor = Executors.newFixedThreadPool(poolSize);
// executor.execute(new Runnable() {
// #Override
// public void run() {
// writeToFile(rawData, storeDir, finalExtension);
// }
// });
logger.info("File uploaded to : " + storeDir);
return "Success 200";
}
I tried to put the writeToFile into threads, but still no success. Here is what writeToFile does
public synchronized void writeToFile(InputStream rawData,
String uploadedFileLocation, String extension) {
StringBuilder finalFileName = null;
String currentIncrement = "";
String fileName = "raw";
try {
File file = new File(uploadedFileLocation);
if (!file.exists()) {
file.mkdirs();
}
while (true) {
finalFileName = new StringBuilder(fileName);
if (!currentIncrement.equals("")) {
finalFileName.append("_").append(currentIncrement).append(extension);
}
File f = new File(uploadedFileLocation + finalFileName);
if (f.exists()) {
if (currentIncrement.equals("")) {
currentIncrement = "1";
} else {
currentIncrement = (Integer.parseInt(currentIncrement) + 1) + "";
}
} else {
break;
}
}
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(new File(uploadedFileLocation + finalFileName));
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
The writeToFile creates a folder and writes a file, if the file already exists, it appends 1 and then increments the 1 accordingly and writes the file, so I would get raw.zip, raw-1.zip, etc.
I think the inputstream bytes are being lost, am I correct in my assumption?
NOTE: I do not have a UI client, I am using Poster a Firefox extension.
Update: What I am trying to achieve here is very simple
I receive number of requests with files attached
I need to save them. If the mediaName and mediaType are the same, then I need to append something to the filename and save it in the same location
If they are different I do not have a problem
The problem I am facing with the current code is that, when I post multiple time to the same URL, I have file-names created according to what I want, but the file content is not right, they vary depending on when the request came in and only the last POST's request is written properly.
Eg. I have a zip file of size 250MB, when I post 5 time, the 1st four will have random sizes and the 5th will have the complete 250MB, but the previous four should also have the same content.
You must separate the stream copy from the free filename assignation. The stream copy must be done within the calling thread (jersey service). Only the file naming operation must be common to all threads/requests.
Here is your code with a little refactoring :
getNextFilename
This file naming operation must be synchronized to guarantee each call gives a free name. This functions creates an empty file to guarantee the next call to work, because the function relies on file.exists().
public synchronized File getNextFilename(String uploadedFileLocation, String extension)
throws IOException
{
// This function MUST be synchronized to guarantee unicity of files names
// Synchronized functions must be the shortest possible to avoid threads waiting each other.
// No long job such as copying streams here !
String fileName = "raw";
//Create directories (if not already existing)
File dir = new File(uploadedFileLocation);
if (!dir.exists())
dir.mkdirs();
//Search for next free filename (raw.<extension>, else raw_<increment>.<extension>)
int currentIncrement = 0;
String finalFileName = fileName + "." + extension;
File f = new File(uploadedFileLocation + finalFileName);
while (f.exists())
{
currentIncrement++;
finalFileName = fileName + "_" + currentIncrement + "." + extension;
f = new File(uploadedFileLocation + finalFileName);
}
//Creates the file with size 0 in order to physically reserve the file "raw_<n>.extension",
//so the next call to getNextFilename will find it (f.exists) and will return "raw_<n+1>.extension"
f.createNewFile();
//The file exists, let the caller fill it...
return f;
}
writeToFile
Must not be synchronized !
public void writeToFile(InputStream rawData, String uploadedFileLocation, String extension)
throws IOException
{
//(1) Gets next available filename (creates the file with 0 size)
File file = getNextFilename(uploadedFileLocation, extension);
//(2) Copies data from inputStream to file
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(file);
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}